builder.HasData(new Role { Id = 1, Name = "SuperAdmin", NormalizedName = "超级管理员" }); builder.HasData(new Role { Id = 2, Name = "Admin", NormalizedName = "管理员" }); builder.HasData(new Role { Id = 3, Name = "Operator", NormalizedName = "操作员" }); } }
using Sample.Identity.ViewModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text;
namespaceSample.Identity.Controllers;
[Route("api/[controller]")] [ApiController] publicclassAuthenticateController : ControllerBase { privatereadonly UserManager<User> m_userManager; privatereadonly RoleManager<Role> m_roleManager; privatereadonly IConfiguration m_configuration; privatereadonly JwtOption m_jwtOptions; publicAuthenticateController(UserManager<User> userManager, RoleManager<Role> roleManager, IConfiguration configuration) { m_userManager = userManager; m_roleManager = roleManager; m_configuration = configuration; m_jwtOptions = m_configuration.GetSection("").Get<JwtOption>(); } [HttpPost] [Route("login")] publicasync Task<IActionResult> Login([FromBody] LoginViewModel model) { var user = await m_userManager.FindByNameAsync(model.Username); if(user!=null && await m_userManager.CheckPasswordAsync(user, model.Password)) { var roles = await m_userManager.GetRolesAsync(user); var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Username); new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) } foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var token = GenerateToken(claims); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }); } return Unauthorized(); } private JwtSecurityToken GetToken(List<Claim> authClaims) { var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(m_jwtOptions.Secret)); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return token; } }