Step 1. 增加配置信息和配置类
增加一个类与配置信息绑定
public class JWTConfig
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string IssuerSigningKey { get; set; }
public int AccessTokenExpiresMinutes { get; set; }
}
appsetting.json
"JWT": {
"Issuer": "AZDigital",
"Audience": "allCustomer",
"IssuerSigningKey": "AZDigital67451147",
"AccessTokenExpiresMinutes": "1440"
}
Step 2. Startup.cs增加
ConfigureServices函数增加
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//services.AddControllers();
//增加报错异常提示
services.AddControllers().AddHttpExceptions();
//这里可以添加注入对象并与配置内容绑定
services.AddOptions();
services.Configure<JWTConfig>(Configuration.GetSection("JWT"));
#region 读取配置文件
JWTConfig config = new JWTConfig();
Configuration.GetSection("JWT").Bind(config);
#endregion
#region 开启JWT
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).
AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = config.Issuer,
ValidAudience = config.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.IssuerSigningKey)),
ClockSkew = TimeSpan.FromMinutes(1),
};
});
#endregion
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AZReport API", Version = "v1" });
});
}
Configure函数增加
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Report V1");
});
// 这里使用http异常信息
app.UseHttpExceptions();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// brerer token 开启使用认证必须加到上下两个函数之间
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Step 3. 创建token的函数
// 创建和认证的时候
// issuer + audience + signingCredentials 和 认证的时候必须一致才行
private string CreateToken()
{
var now = DateTime.Now;
var expires = now.Add(TimeSpan.FromMinutes(_options.Value.AccessTokenExpiresMinutes));
Claim[] claims = { new Claim(ClaimTypes.Email, "admin"), new Claim(ClaimTypes.Name, "admin") };
var token = new JwtSecurityToken(
issuer: _options.Value.Issuer,
audience: _options.Value.Audience,
claims: claims,
notBefore: now,
expires: expires,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Value.IssuerSigningKey)), SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
Step 4. 增加需要认证的控制器
[Route("api/test")]
[Authorize] //添加这个配置
public class ValuesController : ControllerBase
{
[HttpGet("aaa")]
[AllowAnonymous] //这个意思是跳过认证
public string getsss()
{
return "aaaaa";
}
[HttpGet("bbb")]
public string getcccc()
{
return "bbbbb";
}
}
ok。。至此完了。。