How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0
Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub to find the answer.
Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:
[Authorize(Policy = "ServiceRequirement")] | |
public class ExampleHub : Hub | |
{ | |
[Authorize(Policy = "EndpointRequirement")] | |
public Task Register() | |
{ | |
return Task.CompletedTask; | |
} | |
} |
I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different.
Method implementation has a resource type of HubInnovationContext:
I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext. For me I don't even need that, it can be removed completely from the inheritence signature and override implementation.
public class Startup | |
{ | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
app.UseDeveloperExceptionPage(); | |
app.UseRouting(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => endpoints.MapHub<ExampleHub>("/Example")); | |
} | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddSignalR(options => | |
{ | |
options.EnableDetailedErrors = true; | |
}); | |
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) | |
.AddNegotiate(); | |
services.AddAuthorization(options => | |
{ | |
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser() | |
.Build(); | |
options.AddPolicy(nameof(ServiceRequirement), policy => policy.Requirements.Add(new ServiceRequirement())); | |
options.AddPolicy(nameof(EndpointRequirement), policy => policy.Requirements.Add(new EndpointRequirement())); | |
}); | |
services.AddSingleton<IUserIdProvider, NameUserIdProvider>(); | |
services.AddSingleton<IAuthorizationRequirement, EndpointAuthorizationHandler>(); | |
services.AddSingleton<IAuthorizationRequirement, ServiceAuthorizationHandler>(); | |
} | |
} |
Comments
Post a Comment