使用WebAPI Bearer Token进行SignalR身份验证

24

+我使用this solution实现了基于令牌的身份验证,使用了ASP.NET Web API 2、Owin和Identity,效果非常好。我还使用了其他解决方案和这个来实现信号R中心的授权和身份验证,通过连接字符串传递Bearer令牌,但似乎Bearer令牌没有被传递,或者其他地方出了问题,因此在这里寻求帮助...这些是我的代码... QueryStringBearerAuthorizeAttribute:这是负责验证的类

using ImpAuth.Entities;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace ImpAuth.Providers
{
    using System.Security.Claims;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;
    using Microsoft.AspNet.SignalR.Owin;

    public class QueryStringBearerAuthorizeAttribute : AuthorizeAttribute
    {
        public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
        {
            var token = request.QueryString.Get("Bearer");
            var authenticationTicket = Startup.AuthServerOptions.AccessTokenFormat.Unprotect(token);

            if (authenticationTicket == null || authenticationTicket.Identity == null || !authenticationTicket.Identity.IsAuthenticated)
            {
                return false;
            }

            request.Environment["server.User"] = new ClaimsPrincipal(authenticationTicket.Identity);
            request.Environment["server.Username"] = authenticationTicket.Identity.Name;
            request.GetHttpContext().User = new ClaimsPrincipal(authenticationTicket.Identity);
            return true;
        }

        public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
        {
            var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;

            // check the authenticated user principal from environment
            var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
            var principal = environment["server.User"] as ClaimsPrincipal;

            if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
            {
                // create a new HubCallerContext instance with the principal generated from token
                // and replace the current context so that in hubs we can retrieve current user identity
                hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId);

                return true;
            }

            return false;
        }
    }
}

这是我的启动类....

using ImpAuth.Providers;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.Facebook;
using Microsoft.Owin.Security.Google;
//using Microsoft.Owin.Security.Facebook;
//using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;

[assembly: OwinStartup(typeof(ImpAuth.Startup))]

namespace ImpAuth
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions AuthServerOptions;

        static Startup()
        {
            AuthServerOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider()
               // RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };
        }

        public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
        public static GoogleOAuth2AuthenticationOptions googleAuthOptions { get; private set; }
        public static FacebookAuthenticationOptions facebookAuthOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            //app.MapSignalR();
            ConfigureOAuth(app);
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can 
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    //EnableJSONP = true
                    EnableDetailedErrors = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
            HttpConfiguration config = new HttpConfiguration();
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "1062903283154-94kdm6orqj8epcq3ilp4ep2liv96c5mn.apps.googleusercontent.com",
                ClientSecret = "rv5mJUz0epWXmvWUAQJSpP85",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = "CHARLIE",
                AppSecret = "xxxxxx",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);
        }
    }

}

这是客户端的Knockout加jQuery代码...

function chat(name, message) {
    self.Name = ko.observable(name);
    self.Message = ko.observable(message);
}

function viewModel() {
    var self = this;
    self.chatMessages = ko.observableArray();

    self.sendMessage = function () {
        if (!$('#message').val() == '' && !$('#name').val() == '') {
            $.connection.hub.qs = { Bearer: "yyCH391w-CkSVMv7ieH2quEihDUOpWymxI12Vh7gtnZJpWRRkajQGZhrU5DnEVkOy-hpLJ4MyhZnrB_EMhM0FjrLx5bjmikhl6EeyjpMlwkRDM2lfgKMF4e82UaUg1ZFc7JFAt4dFvHRshX9ay0ziCnuwGLvvYhiriew2v-F7d0bC18q5oqwZCmSogg2Osr63gAAX1oo9zOjx5pe2ClFHTlr7GlceM6CTR0jz2mYjSI" };
            $.connection.hub.start().done(function () {
                $.connection.hub.qs = { Bearer: "yyCH391w-CkSVMv7ieH2quEihDUOpWymxI12Vh7gtnZJpWRRkajQGZhrU5DnEVkOy-hpLJ4MyhZnrB_EMhM0FjrLx5bjmikhl6EeyjpMlwkRDM2lfgKMF4e82UaUg1ZFc7JFAt4dFvHRshX9ay0ziCnuwGLvvYhiriew2v-F7d0bC18q5oqwZCmSogg2Osr63gAAX1oo9zOjx5pe2ClFHTlr7GlceM6CTR0jz2mYjSI" };
                $.connection.impAuthHub.server.sendMessage($('#name').val(), $('#message').val())
                            .done(function () { $('#message').val(''); $('#name').val(''); })
                            .fail(function (e) { alert(e) });
            });
        }
    }

    $.connection.impAuthHub.client.newMessage = function (NAME, MESSAGE) {
        //alert(ko.toJSON(NAME, MESSAGE));
        var chat1 = new chat(NAME, MESSAGE);
        self.chatMessages.push(chat1);
    }

}

ko.applyBindings(new viewModel());

这是我的中枢类...

using ImpAuth.Providers;
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ImpAuth
{
    public class impAuthHub : Hub
    {
        [QueryStringBearerAuthorize]
        public void SendMessage(string name, string message)
        {

            Clients.All.newMessage(name, message);
        }
    }
}

现在的问题是当我尝试调用一个经过身份验证的Hub类时,出现了以下错误

caller is not authenticated to invove method sendMessage in impAuthHub

但是我在QueryStringBearerAuthorizeAttribute类中更改了这个方法,使其始终返回true,如下所示

public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod)
{
    var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId;
    // check the authenticated user principal from environment
    var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment;
    var principal = environment["server.User"] as ClaimsPrincipal;

    if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
    {
        // create a new HubCallerContext instance with the principal generated from token
        // and replace the current context so that in hubs we can retrieve current user identity
        hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId);

        return true;
    }

    return true;
}

...它起作用了....我的代码或实现有什么问题?


我已经给那个fork了我的repo并实现了与SignalR集成的Louis发送了一封电子邮件,希望他能够查看并提供帮助。 很高兴我的帖子对你有用 :) - Taiseer Joudeh
你好,Lewis...我得到了一个空值原则...要么是令牌未被发送,顺便问一下,我该如何检查客户端是否发送了令牌? - McKabue
@Louis-Lewis 这个方法 'public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request){}' 似乎在任何时候都没有被调用...为什么?这就是它的作用吗? - McKabue
在你的启动类中,你还创建了一个新的OAuthAuthorizationServerOptions变量。其中有一个全局变量在启动类的构造函数中初始化。将这行代码app.UseOAuthAuthorizationServer(OAuthServerOptions);改为app.UseOAuthAuthorizationServer(AuthServerOptions);。 - Louis Lewis
+谢谢Lewis,当我将属性移到中心类时,它运行得很好,但是它不像之前那样返回错误响应,当bearer token错误或不可用时...我想在fail方法{.fail(function(e){alert(e)});}中捕获错误响应,以便我可以提示客户登录... - McKabue
显示剩余4条评论
3个回答

41

你需要像这样配置你的SignalR;

app.Map("/signalr", map =>
{
    map.UseCors(CorsOptions.AllowAll);

    map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        Provider = new QueryStringOAuthBearerProvider()
    });

    var hubConfiguration = new HubConfiguration
    {
        Resolver = GlobalHost.DependencyResolver,
    };
    map.RunSignalR(hubConfiguration);
});

那么您需要为SignalR编写一个基本的自定义OAuthBearerAuthenticationProvider,该提供程序接受查询字符串中的access_token。

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<object>(null);
    }
}

之后,您所需的只是将access_token作为查询字符串与signalr连接一起发送。

$.connection.hub.qs = { 'access_token': token };

对于您的中心,只需要使用普通的[Authorize]属性即可。

public class impAuthHub : Hub
{
    [Authorize]
    public void SendMessage(string name, string message)
    {
       Clients.All.newMessage(name, message);
    }
}

希望这可以帮助到您。YD。


你如何从中心“Context”访问用户?你能调用Context.User.Identity.Name吗?这行代码具体是做什么的? context.Token = value;它是如何填充中心上下文的呢? 谢谢! - radu-matei
7
我刚刚尝试了这种方法,但不幸的是,我的 Context.User.Identity.Namenull - radu-matei
1
Provider 中的 context 在 OWIN 管道中的哪个位置?我将 context.Token 设置为从客户端检索到的令牌,这个事实会如何影响我的 Context?如果有任何存储库/更复杂的示例,现在对我来说都是宝贵的。谢谢! - radu-matei
1
@tofutim,我实际上为此创建了一个仓库,你可以在这里找到它 - radu-matei
2
@radu-matei,请问您能否检查一下仓库,链接已经失效了 - 我在仓库中看到项目已经重构。这个链接是否正确?这个是正确的链接吗? - Johan Aspeling
显示剩余12条评论

3

在Peter的优秀答案下无法进行评论,因此我添加了我的答案。

进一步挖掘后,我发现我自定义的OWIN授权提供程序中设置的用户ID隐藏在这里(完整的hub方法显示如下)。

    [Authorize]
    public async Task<int> 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;
    }

以下是对 texas697 的补充:

如果 Startup.Auth.cs 中没有添加以下代码,请在 ConfigureAuth() 方法中添加:

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

自定义的认证提供程序如下所示:
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<object>(null);
    }
}

2
这个有用吗?我收到错误信息:调用者未被授权在<Hub>上调用<method>方法。 我可以看到请求令牌已经正确执行,并且令牌被赋予了正确的值。 - Deepak Sharma

2

我参照了这里的方法:

首先将JWT添加到查询字符串中:

this.connection = $['hubConnection']();
this.connection.qs = { 'access_token': token}

然后在 startup.cs 文件中,在 JwtBearerAuthentication 之前将令牌添加到标头:

 app.Use(async (context, next) =>
            {
                if (string.IsNullOrWhiteSpace(context.Request.Headers["Authorization"]) && context.Request.QueryString.HasValue)
                {
                    var token = context.Request.QueryString.Value.Split('&').SingleOrDefault(x => x.Contains("access_token"))?.Split('=')[1];
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        context.Request.Headers.Add("Authorization", new[] { $"Bearer {token}" });
                    }
                }
                await next.Invoke();
            });


            var keyResolver = new JwtSigningKeyResolver(new AuthenticationKeyContainer());
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidAudience = ConfigurationUtil.ocdpAuthAudience,
                        ValidIssuer = ConfigurationUtil.ocdpAuthZero,
                        IssuerSigningKeyResolver = (token, securityToken, kid, validationParameters) => keyResolver.GetSigningKey(kid)
                    }
                });


            ValidateSignalRConnectionData(app);
            var hubConfiguration = new HubConfiguration
            {
                EnableDetailedErrors = true
            };
            app.MapSignalR(hubConfiguration);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接