首先Nuget中引入库:
Microsoft.AspNetCore.Authentication.JwtBearer
1、注入
Startup里ConfigureServices方法里
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; });
Configure方法里:
app.UseAuthentication();
2、
using System.IdentityModel.Tokens.Jwt; using Microsoft.IdentityModel.Tokens;
3、CreateToken的方法
private string CreateToken(string userId, string userName) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), }; var a= _configuration["Jwt:Key"]; a = _configuration["Jwt:Issuer"]; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"], claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(token); }
4、控制器中登录方法
[HttpPost] public IActionResult Login(UserModel model) { IActionResult response = Unauthorized(); var userInfo = CheckUser(model); if (userInfo != null) { var tokenString = CreateToken(userInfo.UserId, userInfo.UserName); response = Ok(new {token = tokenString}); } return response; } private User CheckUser(UserModel model) { return new User() {UserId = "123456789", UserName = "test"}; }
public class UserModel { public string UserName { get; set; } public string Password { get; set; } }
5、Postman调试接口查看效果