SignalR authentication with webAPI Bearer Token

前端 未结 3 1221
悲哀的现实
悲哀的现实 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:36

    I followed this:

    first Add the JWT to the query string:'

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

    then in thestartup.cs,before JwtBearerAuthentication, add the token to the 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);
    

提交回复
热议问题