什么是JWT,什么是JWT Bearer就不累述了。在ASP.NET WEBAPI中使用JWT Bearer的时候比较多,最近我终于学会配置了。
第一步:对应项目安装Microsoft.AspNetCore.Authentication.JwtBearer
第二步:appsettings.json中,添加JWT的配置,参考代码如下,注意SecretKey不能设置成太短的纯数字,不然要报错
{
"Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "JWT": { "SecretKey": "weblog@vip.qq.com", "Issuer": "2222", "Expires": 10, "Audience": "22333" } }
第三步:在Program.cs中,将JWT添加到服务中,参考代码
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = builder.Configuration["JWT:Issuer"], ValidateAudience = true, ValidAudience = builder.Configuration["JWT:Audience"], ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"])) }; });
第四步:在Program.cs中,启用认证,添加代码如下,这个必须添加在app.UseAuthorization();
前面,两个名称很像,注意区别。
app.UseAuthentication();
第五:创建一个方法,专门用来生成JWT的Token,参考代码
public string CreateToken() { // 1. 定义需要使用到的Claims var claims = new[] { new Claim("Id", "9527"), new Claim("Name", "Admin") }; // 2. 从 appsettings.json 中读取SecretKey var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"])); // 3. 选择加密算法 var algorithm = SecurityAlgorithms.HmacSha256; // 4. 生成Credentials var signingCredentials = new SigningCredentials(secretKey, algorithm); // 5. 从 appsettings.json 中读取Expires var expires = Convert.ToDouble(configuration["JWT:Expires"]); // 6. 根据以上,生成token var token = new JwtSecurityToken( configuration["JWT:Issuer"], //Issuer configuration["JWT:Audience"], //Audience claims, //Claims, DateTime.Now, //notBefore DateTime.Now.AddDays(expires), //expires signingCredentials //Credentials ); // 7. 将token变为string var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); return jwtToken; }
注意:claims里面的内容应该要从外面创建来,动态存一些用户信息之类的;configuration["JWT:SecretKey"]
这种是在读取配置文件appsettings.json
中的配置,configuration
要在类的构造函数中注入进来。
第六,找到有关登录方法的控制器,在登录成功之后,将token返回给用户,参考代码
public IActionResult Login(LoginDto loginDto) { if (!ModelState.IsValid) { return BadRequest("Email or Password can not be empty"); } var token = _makeToken.CreateToken(); return Ok(token); }
第七,在对应业务的控制器上,或者控制器下面的方法上,加上特性[Authorize]
就这样,.NET 6实现了基本的 JWT Bearer认证和授权配置。