How to create custom authentication mechanism based on HTTP header?

前端 未结 2 779
庸人自扰
庸人自扰 2020-12-30 08:25

I\'m leaving old version of question on a bottom.

I\'d like to implement custom authentication for SignalR clients. In my case this is java clients (Android). Not we

相关标签:
2条回答
  • 2020-12-30 08:41

    So I just created a custom Authorization Attribute and overrode the AuthorizeHubConnection method to get access to the request and implemented the logic that you were trying to do with the Header and it appears to be working.

    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    
    namespace SignalR.Web.Authorization
    {
        public class HeadersAuthAttribute : AuthorizeAttribute
        {
            private const string UserIdHeader = "SRUserId";
    
            public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
            {
                if (string.IsNullOrEmpty(request.Headers[UserIdHeader]))
                {
                    return false;
                }
    
                return true;
            }
        }
    }
    

    Hub

     [HeadersAuth]
        [HubName("messagingHub")]
        public class MessagingHub : Hub
        {
    
        }
    

    Which yields this in the console (if the picture doesn't show up, it's a [Failed to load resource: the server responded with a status of 401 (Unauthorized)]):

    0 讨论(0)
  • 2020-12-30 08:53

    In fact, accepted answer is wrong. Authorization attribute, surprisingly, shall be used for authorization (that is, you should use it for checking whether requesting authenticated user is authorized to perform a desired action).

    Also, since you using incorrect mechanics, you don't have HttpContext.Current.User.Identity set. So, you have no clear way to pass user info to your business / authorization logic.

    And third, doing that you won't be able to use Clients.User() method to send message to specific user, since SignalR will be not able to map between users and connections.

    The correct way is to plug in into OWIN authentication pipeline. Here is an excellent article explaining and demonstrating in detail how to implement custom authentication to be used in OWIN.

    I not going to copy-paste it here, just follow it and make sure you implement all required parts:

    • Options
    • Handler
    • Middleware

    After you have these, register them into OWIN:

    app.Map("/signalr", map =>
    {
       map.UseYourCustomAuthentication();
    
       var hubConfiguration = new HubConfiguration
       {
           Resolver = GlobalHost.DependencyResolver,
       };
    
       map.RunSignalR(hubConfiguration);
    });
    
    0 讨论(0)
提交回复
热议问题