注册认证服务
- 在这里,我们用微软给我们提供的JwtBearer认证方式,实现认证服务注册 。
引入nuget包:Microsoft.AspNetCore.Authentication.JwtBearer
- 注册服务,将服务添加到容器中
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var Issurer = "JWTBearer.Auth"; //发行人
var Audience = "api.auth"; //受众人
var secretCredentials = "q2xiARx$4x3TKqBJ"; //密钥
//配置认证服务
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o=>{
o.TokenValidationParameters = new TokenValidationParameters
{
//是否验证发行人
ValidateIssuer = true,
ValidIssuer = Issurer,//发行人
//是否验证受众人
ValidateAudience = true,
ValidAudience = Audience,//受众人
//是否验证密钥
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretCredentials)),
ValidateLifetime = true, //验证生命周期
RequireExpirationTime = true, //过期时间
};
});
}
- 注意说明:
一. TokenValidationParameters的参数默认值:
1. ValidateAudience = true, ----- 如果设置为false,则不验证Audience受众人
2. ValidateIssuer = true , ----- 如果设置为false,则不验证Issuer发布人,但建议不建议这样设置
3. ValidateIssuerSigningKey = false,
4. ValidateLifetime = true, ----- 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
5. RequireExpirationTime = true, ----- 是否要求Token的Claims中必须包含Expires
6. ClockSkew = TimeSpan.FromSeconds(300), ----- 允许服务器时间偏移量300秒,即我们配置的过期时间加上这个允许偏移的时间值
调用方法,配置Http请求管道
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
//1.先开启认证
app.UseAuthentication();
//2.再开启授权
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
- 在JwtBearerOptions的配置中,通常IssuerSigningKey(签名秘钥), ValidIssuer(Token颁发机构), ValidAudience(颁发给谁) 三个参数是必须的,后两者用于与TokenClaims中的Issuer和Audience进行对比,不一致则验证失败
接口资源保护
[ApiController]
[Route("[controller]")]
[Authorize]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
生成Token
运行
访问获取Token方法,获取得到access_token
再访问,授权资源接口,可以发现,再没有添加请求头token值的情况下,返回了401没有权限
这次,在请求头通过Authorization加上之前获取的token值后,再次进行访问,发现已经可以获取访问资源控制器,并返回对应的数据