asp.net - ASP Core 3 上的 JWT + SignalR 导致 401 Unauthorized
问题描述
如果我在 signalr 之外使用 http 调用,例如使用 postman 或 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();
解决方案
解决。
问题是我覆盖了 的OnMessageReceived
处理程序,JwtBearerHandler
然后让它自己读取传入的令牌......但是我传递给它的令牌包含前缀Bearer
,当由上述处理程序解析时,它与现有的已知令牌不匹配用户。
只需删除我的覆盖OnMessageReceived
并让 AspNetCore 的默认实现JwtBearerHandler
完成其工作即可使令牌解析正常工作。
推荐阅读
- crash - 导入dill和dump session后,无法打开notebook,无法找回代码
- java - 在wiremock中,是否可以在请求中记录cookie?
- c++ - c++ stl中deque是如何实现的
- ubuntu - 升级 intellij 2018 -> 2019 的最简单方法?
- python - 将 csv 文件读取到 dask 和 pandas 中的数据框时出错
- ionic-framework - 密钥库文件不存在。无法获取 SHA1 密钥
- scala - 尝试在 Scala 中并行化嵌套循环
- sql - 使用多个过滤器和创建表的 Oracle SQL 查询优化
- android - Android 应用程序可以在设备锁定时继续播放声音吗?
- javascript - 调用跨域API的IE9兼容模式问题