2
votes

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));
                        })
2

2 Answers

1
votes

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
{

} 
0
votes

You can do it by adding authorization data to the route.

app.UseSignalR(routes =>
{
   routes.MapHub<BackgroundServiceHub>("/hubs", o =>
   {
      o.AuthorizationData.Add(new AuthorizeAttribute());
   });
});