How to create custom authentication mechanism based on HTTP header?

前端 未结 2 778
庸人自扰
庸人自扰 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)]):

提交回复
热议问题