在Asp .net core中使用Jwt登录验证
-
安装Jwt Nuget包

-
在startup中添加验证授权中间件(在路由之后)

-
在appsettings中添加Jwt所需配置

-
在登录控制器中创建Jwt
var signingAlgorithm = SecurityAlgorithms.HmacSha256; var claims = new List{ new Claim(JwtRegisteredClaimNames.Sub, user.Id), }; var roleNames = await _userManager.GetRolesAsync(user); foreach (var roleName in roleNames) { var roleClaim = new Claim(ClaimTypes.Role, roleName); claims.Add(roleClaim); } var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]); var signingkey = new SymmetricSecurityKey(secretByte); var signingCredentials = new SigningCredentials(signingkey, signingAlgorithm); var token = new JwtSecurityToken( issuer: _configuration["Authentication:Issuer"], audience: _configuration["Authentication:Audience"], claims, notBefore: DateTime.UtcNow, expires: DateTime.UtcNow.AddDays(1), signingCredentials ); var tokenStr = new JwtSecurityTokenHandler().WriteToken(token); -
ConfigureServices中配置jwt

-
在需要验证是否登录的Action加上Attribute
[Authorize(AuthenticationSchemes = "Bearer")]