运行一个基本的Core RESTful服务器,我正在使用我在端点上提供的JWT令牌来保护我的端点(这是目前的概念验证)。当我使用Postman进行测试时,我能够正确地进行身份验证,但是,从控制台应用程序中,得到401,Unauthorized。
下面是我在ServiceExtensions类中的内容。
public static IServiceCollection ConfigureJwtAuthentication(this IServiceCollection services,
IConfiguration config)
{
var section = config.GetSection("Jwt");
var jwtOptions = section.Get<JwtConfigOptions>();
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
//options.Authority = jwtOptions.AuthorityUrl;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = jwtOptions.SymmetricSecurityKey
};
});
return services;
}
这是我的JwtConfigOptions类。
public class JwtConfigOptions
{
public string Key { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public string AuthorityUrl { get; set; }
public string AudienceUrl { get; set; }
public SymmetricSecurityKey SymmetricSecurityKey => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key));
}
并在appsettings.json中设置了值 所以我在创建和审核token时使用了相同的值
有什么方法可以记录为什么给定的token被拒绝?
谢谢你
我能够找到一个答案。我发现 本网站 其中有一个github解决方案的链接,其中有Microsoft.AspNetCore.Authentication.JwtBearer汇编中的项目的源代码。我附加到了JwtBearerHandler项目中,并能够逐步完成代码。原来我在头中对bearer token进行了错误的编码。其实在红脸之前已经把正确的代码注释掉了一行。