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

时间:2019-05-28 13:35:17

标签: asp.net asp.net-core signalr asp.net-identity

如果我在Signalr之外使用http调用(例如与邮递员或httpclient一起使用),则可以在服务器上成功验证我的令牌。当我尝试通过信号中心进行连接时,令牌未通过授权。

  

承载者未通过身份验证。失败消息:令牌没有可用的SecurityTokenValidator:Bearer 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();

1 个答案:

答案 0 :(得分:0)

已解决。

问题是我要覆盖OnMessageReceived的{​​{1}}处理程序,然后让它自己读取传入的令牌...但是我传递的令牌包含前缀{{1} },由上述处理程序进行解析时,与现有用户的已知令牌不匹配。

只需删除我对JwtBearerHandler的覆盖,并让AspNetCore的Bearer的愚蠢实现执行其工作,就可以使令牌解析正常进行。