未调用SignalR Authorize属性

时间:2015-06-21 21:56:48

标签: asp.net-web-api authorization signalr jwt authorize

我有一个集线器,它不会将位于Authorization:Bearer eyjsdalfsadlfjffdafs ...的令牌转换为请求标头中的标识。 API的其余部分可以与标准的http动词一起使用,但由于某种原因,SignalR没有将令牌授权给用户。

public class ChatHub : Hub
{
   [Authorize]
    public override Task OnConnected()
    {
         // error context.user.identity.name =""
        var userId = int.Parse(Context.User.Identity.Name); 


        return base.OnConnected();
    }
....
}

Startup.cs

    public class Startup
{
    public void Configuration(IAppBuilder app)
    {
  app.MapSignalR(); 


    }
}

JwtHandler - 即使onConnect()归因于[Authorize]

,客户端连接到集线器时也不会调用此部分过滤器
  public class JwtHandler : DelegatingHandler
{
    private const string ISSUER = "Issuer";
    private const string AUDIENCE = "Audience";          
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        byte[] key = Convert.FromBase64String("SecretKey");
        try
        {
            var headers = request.Headers;
            if(headers.Authorization != null)
            {
                if(headers.Authorization.Scheme.Equals("Bearer"))
                {
                    string jwt = request.Headers.Authorization.Parameter;
                    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                    TokenValidationParameters parms = new TokenValidationParameters()
                    {
                        ValidAudience = AUDIENCE,
                        ValidIssuers = new List<string>(){ISSUER},
                        IssuerSigningToken = new BinarySecretSecurityToken(key),

                    };
                    SecurityToken validated = new JwtSecurityToken(jwt);

                    var principal = tokenHandler.ValidateToken(jwt, parms,out validated);
                    Thread.CurrentPrincipal = principal;

                    if(HttpContext.Current !=null)
                    {
                        HttpContext.Current.User = principal;
                    }

                }

            } 
            var response = await base.SendAsync(request, cancellationToken);
                if(response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Bearer", "error=\"invalid_token\""));
                    return response;
                }
                return response;
        }catch (Exception)
        {
            var response = request.CreateResponse(HttpStatusCode.Unauthorized);
            response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Bearer", "error=\"invalid_token\""));
            return response;
        }
       }
 }

1 个答案:

答案 0 :(得分:0)

尝试验证OWIN中间件中的jwt令牌。在你的Startup.cs中添加:

public void Configuration(IAppBuilder app)
{
  app.UseJwtBearerAuthentication(
     new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions() {
        AllowedAudiences = new string[] { ALLOWEDAUDIENCE },
        IssuerSecurityTokenProviders = new[] { 
                    new SymmetricKeyIssuerSecurityTokenProvider(ISSUER, System.Convert.FromBase64String(cKey)) 
     }
  });
  app.MapSignalR(); 
}