目录
- 模块拆分
- 代码重构
模块拆分
代码重构
- AuthenticationController
- PermissionController
- IAuthorizationMiddlewareResultHandler
- ISaveChangesInterceptor
AuthenticationController
新增 AuthenticationController 用于登录和注册;登录会颁发 jwt token,包含用户的 claims 和 role 的 claims
登录
[HttpPost]
[Route("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest.LoginModel model)
{
var user = await _userManager.FindByNameAsync(model.Username);
var userClaims = await _userManager.GetClaimsAsync(user);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
var userRoles = await _userManager.GetRolesAsync(user);
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
foreach (var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
var role = await _roleManager.FindByNameAsync(userRole);
var roleClaims = await _roleManager.GetClaimsAsync(role);
authClaims.AddRange(roleClaims);
}
authClaims.AddRange(userClaims);
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT: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 Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
注册
[HttpPost]
[Route("register")]
public async Task<IActionResult> Register([FromBod