【问题标题】:SignalR authentication with webAPI Bearer Token使用 webAPI Bearer Token 的 SignalR 身份验证
【发布时间】:2014-12-26 17:56:57
【问题描述】:

+我使用this solution 使用 ASP.NET Web API 2、Owin 和 Identity 实现基于令牌的身份验证......效果非常好。我用这个other solution和这个通过连接字符串传递承载令牌来实现signalR集线器授权和身份验证,但似乎承载令牌没有去,或者其他地方有问题,这就是为什么我在这里寻求帮助...这些是我的代码... 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);
        }
    }

}

这是客户端上的淘汰赛加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);
        }
    }
}

...现在问题来了,当我尝试调用经过身份验证的集线器类时,我得到了这个错误

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

...它有效....我的代码或实现有什么问题?

【问题讨论】:

  • 我已经向 Louis 发送了一封电子邮件,他分叉了我的 repo 并实现了与 SignalR 的集成,希望他能够检查并提供帮助。很高兴我的帖子对你有用:)
  • 嗨,Taiseer 感谢您的电子邮件。 McKabue,我能想到一些事情。首先,您能否调试您的应用程序并在我们设置 var principal 的那一行中断它。我想看看原则上有什么价值观。这将是最好的起点。
  • +hello Lewis...我得到一个空原则值...不记名令牌没有被发送,购买方式,我如何检查不记名令牌是否从发送客户?
  • +@Louis-Lewis 这个方法 'public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request){}' 似乎在任何给定点都没有被调用...为什么?应该是这样吗?
  • 快速初步了解一下,您已经在方法上而不是在类上分配了属性,我想说这就是 AuthorizeHubConnection 方法没有触发的原因。我建议作为一个起点,尝试将属性移到类上,然后我们从那里拿东西。

标签: c# authentication asp.net-web-api token signalr.client


【解决方案1】:

你需要像这样配置你的信号器;

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 作为查询字符串。

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

对于您的集线器来说,只是普通的 [Authorize] 属性

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

希望这会有所帮助。码。

【讨论】:

  • 您将如何从集线器Context 访问用户?你能打电话给Context.User.Identity.Name吗?这条线到底是做什么的? context.Token = value; 它如何填充集线器上下文?谢谢!
  • 我刚试过这个方法,可惜我的Context.User.Identity.Namenull
  • Provider 中的 context 在哪里适合 OWIN 管道?我将context.Token 设置为从客户端检索到的令牌这一事实将如何影响我的Context?任何回购/更复杂的例子现在对我来说都是黄金。谢谢!
  • @tofutim 我实际上为此创建了一个 repo,you can find it here
  • @radu-matei 请你检查一下 repo,链接已损坏 - 我在 repo 上看到项目已重组。 this 是正确的链接吗?
【解决方案2】:

无法评论,所以在彼得的优秀答案的 cmets 之后添加我的答案。

做了更多的挖掘,我在自定义 owin 授权提供程序中设置的用户 ID 隐藏在这里(显示了完整的集线器方法)。

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

【讨论】:

  • 这行得通吗?我收到错误:调用者无权调用 上的 方法。我可以看到请求令牌被正确执行并且令牌被分配了正确的值。
【解决方案3】:

我关注了this

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

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

然后在startup.cs,在JwtBearerAuthentication之前,将token添加到header中:

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

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多