SignalR authentication with webAPI Bearer Token

前端 未结 3 1219
悲哀的现实
悲哀的现实 2021-01-31 05:01

+i used this solution to implement Token Based Authentication using ASP.NET Web API 2, Owin, and Identity...which worked out excellently well. i used this other solution and thi

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-31 05:23

    Can't comment so adding my answer after the comments on Peter's excellent answer.

    Did a bit more digging and the user id that I had set in my custom owin authorization provider was hiding here (complete hub method shown).

        [Authorize]
        public async Task Test()
        {
            var claims = (Context.User.Identity as System.Security.Claims.ClaimsIdentity).Claims.FirstOrDefault();
            if (claims != null)
            {
                var userId = claims.Value;
    
                //security party!
                return 1;
            }
    
            return 0;
        }
    

    More added for texas697:

    Startup.Auth.cs add this to ConfigureAuth() if not already there:

    app.Map("/signalr", map =>
        {
            map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                Provider = new QueryStringOAuthBearerProvider() //important bit!
            });
    
            var hubConfiguration = new HubConfiguration
            {
                EnableDetailedErrors = true,
                Resolver = GlobalHost.DependencyResolver,
            };
            map.RunSignalR(hubConfiguration);
        });
    

    The custom auth provider looks like this:

    public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
    {
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            var value = context.Request.Query.Get("access_token");
    
            if (!string.IsNullOrEmpty(value))
            {
                context.Token = value;
            }
    
            return Task.FromResult(null);
        }
    }
    
        

    提交回复
    热议问题