ASP Core 3 上的 JWT + SignalR 导致 401 未经授权



如果我在信号器之外使用 http 调用,例如使用邮递员或 httpclient,我能够在服务器上成功验证我的令牌。当我尝试通过我的信号集线器进行连接时,令牌没有通过授权。

持有者未通过身份验证。失败消息:没有可用于令牌的安全令牌验证器:持有者MyTokenFooBar

我的服务设置是:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRouting();
    services.AddControllers();
    services.AddHealthChecks();
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder => { builder.ConnectionString = _configuration.GetConnectionString("DefaultConnection"); }));
    services.AddIdentity<ApplicationUser, IdentityRole>(setup =>
    {
        // foo
    }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration["Jwt:Issuer"],
                ValidAudience = _configuration["Jwt:Audience"],
                ValidateIssuer = false,
                ValidateAudience = false,
                ValidateIssuerSigningKey = false,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])),
                ValidateLifetime = false
            };
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var path = context.HttpContext.Request.Path;
                    if (!path.StartsWithSegments("/chat")) return Task.CompletedTask;
                    var accessToken = context.Request.Headers[HeaderNames.Authorization];
                    if (!string.IsNullOrWhiteSpace(accessToken) && context.Scheme.Name == JwtBearerDefaults.AuthenticationScheme)
                    {
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
        });
    services.AddAuthorization();
    services.AddSignalR(options => { options.EnableDetailedErrors = true; });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(options =>
    {
        options.MapHealthChecks("/health");
        options.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
    app.UseSignalR(options => { options.MapHub<ChatHub>("/chat"); });
}

我使用基本的 http auth 标头进行初始连接,这会将用户登录到标识并生成 jwt 令牌作为响应,以便在将来的调用中使用。

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
    var (headerUserName, headerPassword) = GetAuthLoginInformation(HttpContext);
    var signInResult = await _signInManager.PasswordSignInAsync(headerUserName, headerPassword, false, false);
    if (!signInResult.Succeeded)
    {
        return Unauthorized();
    }
    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperTopSecretKeyThatYouDoNotGiveOutEver!"));
    var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
    var jwt = new JwtSecurityToken(signingCredentials: signingCredentials);
    var handler = new JwtSecurityTokenHandler();
    var token = handler.WriteToken(jwt);
    return new OkObjectResult(token);
}

我的客户端(控制台应用程序(被设置为缓存此令牌并在将来的信号器调用中使用它,如下所示:

获取令牌:

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes($"{userName}:{password}")));
var response = await _client.SendAsync(request); // this goes to the login action posted above
_token = await response.Content.ReadAsStringAsync();

_hubConnection = new HubConnectionBuilder()
    .WithUrl(new Uri(_baseAddress, "chat"),
        options => { options.AccessTokenProvider = () => Task.FromResult(_token); }) // send the cached token back with every request
    .Build();
// here is where the error occurs. 401 unauthorized comes back from this call.
await _hubConnection.StartAsync();

已解决。

问题是我覆盖了JwtBearerHandlerOnMessageReceived处理程序,然后让它自己读取传入的令牌......但是我传递它的令牌包括前缀Bearer,当由上述处理程序解析时,它与现有用户的已知令牌不匹配。

只需删除我对OnMessageReceived的覆盖,并让 AspNetCore 对JwtBearerHandler的繁琐实现完成其工作,就可以使令牌解析正常工作。

相关内容

  • 没有找到相关文章

最新更新