不检查 Asp 核心 3 中的令牌验证
not check Token validation in Asp core 3
我需要检查令牌验证:
public static void AddJWTAuthnticationInjection(this IServiceCollection services,SiteSetting siteSetting)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var securityKey = Encoding.UTF8.GetBytes(siteSetting.JwtSetting.SecretKey);
var ValidatePrameters = new TokenValidationParameters
{
//Tlorance for Expire Time and Befor Time of Token .
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(securityKey),
// I Need Check Expire Token or Not
RequireExpirationTime = true,
ValidateLifetime = true,
ValidateAudience = true,
ValidAudience = siteSetting.JwtSetting.Audience,
ValidateIssuer = true,
ValidIssuer = siteSetting.JwtSetting.Issuer
};
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = ValidatePrameters;
});
}
我在项目中使用了这个中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials()
);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
这是我的服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<CreateRoleValidator>());
services.Configure<SiteSetting>(Configuration.GetSection(nameof(SiteSetting)));
services.AddControllers().AddControllersAsServices();
services.AddContext(Configuration);
services.AddLoginngBehavior();
services.RegisterRedis(Configuration);
services.AddMediatR();
services.AddCors();
services.Injection();
**services.AddJWTAuthnticationInjection(_siteSetting);**
}
但是当我在这个控制器中发送带有令牌的请求时:
[Authorize]
[Pemission("مدیریت نقش ها")]
public class RoleController : BaseController
{
[HttpGet]
[Authorize]
[Pemission("لیست نقش ها")]
public async Task<ReturnResult<IList<Role>>> GetRoles()
{
var result = await mediator.Send(new GetAllRoleQuery());
if (result.Success)
{
return Ok(result.Result);
}
return BadRequest(result.ErrorMessage);
}
}
当我开始这个项目时它得到了这个服务AddJWTAuthnticationInjection
但是当我发送一个请求时它没有检查它。
它没有检查令牌 Validation 。并告诉我 UnAuthorize
。有什么问题 ?我该如何解决这个问题???
您的代码中没有任何内容看起来会因为配置错误而跳出,但是当我过去尝试解决类似问题时,我会检查一些内容:
检查WWW-Authenticate响应Header
默认情况下 asp.net 将添加一个 WWW-Authenticate
header 可以揭示失败的原因。它可以帮助您追踪问题(例如,密钥是否无效?还是观众?)。 header 值类似于 Bearer error="invalid_token", error_description="The token is expired"
.
令牌是否有效?
将您的令牌复制并粘贴到 jwt.io。到期时间是否符合您的预期?检查issuer/audience等
检查身份验证事件
JwtBearerOptions
有一个 Events
property 可用于挂钩不同的事件并有助于追踪问题。下面是将这些连接起来的示例,在每个事件中添加断点或记录可能非常方便。
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents {
OnChallenge = context => {
Console.WriteLine("OnChallenge:");
return Task.CompletedTask;
},
OnAuthenticationFailed = context => {
Console.WriteLine("OnAuthenticationFailed:");
return Task.CompletedTask;
},
OnMessageReceived = context => {
Console.WriteLine("OnMessageReceived:");
return Task.CompletedTask;
},
OnTokenValidated = context => {
Console.WriteLine("OnTokenValidated:");
return Task.CompletedTask;
},
};
关闭验证
您有 true
用于 TokenValidationParameters
的所有验证事件。将它们设置为 false
,然后分别启用每一个以查看导致问题的原因。
您的代码应该可以工作您的令牌似乎无效。将一些验证参数值更改为 false
,如以下代码:
var ValidatePrameters = new TokenValidationParameters
{
//Tlorance for Expire Time and Befor Time of Token .
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(securityKey),
// I Need Check Expire Token or Not
RequireExpirationTime = true,
ValidateLifetime = false,
ValidateAudience = false,
ValidAudience = siteSetting.JwtSetting.Audience,
ValidateIssuer = false,
ValidIssuer = siteSetting.JwtSetting.Issuer
};
然后使用 "jwt.io" 上的 SecurityKey
检查令牌的内容。
此外,如果您使用的是基于策略的身份验证,则应注册“مدیریت نقش ها”策略。
我需要检查令牌验证:
public static void AddJWTAuthnticationInjection(this IServiceCollection services,SiteSetting siteSetting)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var securityKey = Encoding.UTF8.GetBytes(siteSetting.JwtSetting.SecretKey);
var ValidatePrameters = new TokenValidationParameters
{
//Tlorance for Expire Time and Befor Time of Token .
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(securityKey),
// I Need Check Expire Token or Not
RequireExpirationTime = true,
ValidateLifetime = true,
ValidateAudience = true,
ValidAudience = siteSetting.JwtSetting.Audience,
ValidateIssuer = true,
ValidIssuer = siteSetting.JwtSetting.Issuer
};
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = ValidatePrameters;
});
}
我在项目中使用了这个中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials()
);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
这是我的服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<CreateRoleValidator>());
services.Configure<SiteSetting>(Configuration.GetSection(nameof(SiteSetting)));
services.AddControllers().AddControllersAsServices();
services.AddContext(Configuration);
services.AddLoginngBehavior();
services.RegisterRedis(Configuration);
services.AddMediatR();
services.AddCors();
services.Injection();
**services.AddJWTAuthnticationInjection(_siteSetting);**
}
但是当我在这个控制器中发送带有令牌的请求时:
[Authorize]
[Pemission("مدیریت نقش ها")]
public class RoleController : BaseController
{
[HttpGet]
[Authorize]
[Pemission("لیست نقش ها")]
public async Task<ReturnResult<IList<Role>>> GetRoles()
{
var result = await mediator.Send(new GetAllRoleQuery());
if (result.Success)
{
return Ok(result.Result);
}
return BadRequest(result.ErrorMessage);
}
}
当我开始这个项目时它得到了这个服务AddJWTAuthnticationInjection
但是当我发送一个请求时它没有检查它。
它没有检查令牌 Validation 。并告诉我 UnAuthorize
。有什么问题 ?我该如何解决这个问题???
您的代码中没有任何内容看起来会因为配置错误而跳出,但是当我过去尝试解决类似问题时,我会检查一些内容:
检查WWW-Authenticate响应Header
默认情况下 asp.net 将添加一个 WWW-Authenticate
header 可以揭示失败的原因。它可以帮助您追踪问题(例如,密钥是否无效?还是观众?)。 header 值类似于 Bearer error="invalid_token", error_description="The token is expired"
.
令牌是否有效?
将您的令牌复制并粘贴到 jwt.io。到期时间是否符合您的预期?检查issuer/audience等
检查身份验证事件
JwtBearerOptions
有一个 Events
property 可用于挂钩不同的事件并有助于追踪问题。下面是将这些连接起来的示例,在每个事件中添加断点或记录可能非常方便。
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents {
OnChallenge = context => {
Console.WriteLine("OnChallenge:");
return Task.CompletedTask;
},
OnAuthenticationFailed = context => {
Console.WriteLine("OnAuthenticationFailed:");
return Task.CompletedTask;
},
OnMessageReceived = context => {
Console.WriteLine("OnMessageReceived:");
return Task.CompletedTask;
},
OnTokenValidated = context => {
Console.WriteLine("OnTokenValidated:");
return Task.CompletedTask;
},
};
关闭验证
您有 true
用于 TokenValidationParameters
的所有验证事件。将它们设置为 false
,然后分别启用每一个以查看导致问题的原因。
您的代码应该可以工作您的令牌似乎无效。将一些验证参数值更改为 false
,如以下代码:
var ValidatePrameters = new TokenValidationParameters
{
//Tlorance for Expire Time and Befor Time of Token .
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(securityKey),
// I Need Check Expire Token or Not
RequireExpirationTime = true,
ValidateLifetime = false,
ValidateAudience = false,
ValidAudience = siteSetting.JwtSetting.Audience,
ValidateIssuer = false,
ValidIssuer = siteSetting.JwtSetting.Issuer
};
然后使用 "jwt.io" 上的 SecurityKey
检查令牌的内容。
此外,如果您使用的是基于策略的身份验证,则应注册“مدیریت نقش ها”策略。