I'm working on ASP.Net Core 2.2 Web Service + SignarR Core with JWT authentication and want ensure that all my hubs could be accessed only with valid token.
I can set [Authorize] attribute on all hubs to ensure that, but is it possible to require authorization by default (otherwise one can forget it when implementing a new hub in the future).
Just like I can do it for controllers:
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
For global checking the Authorized user, you could try
Options1: configure middleware to authorize before signalR
app.Use(async (context, next) =>
{
if (context.User.Identity.IsAuthenticated)
{
await next.Invoke();
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
});
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/hubs/chat");
});
Options2: Implement the base hub, and other hubs inherited from this base hub
[Authorize]
public class AuthorizeHub:Hub
{
}
public class OtherHub: AuthorizeHub
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With