| | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | 2 | | using System.Security.Claims; |
| | 3 | | using System.Text; |
| | 4 | | using Microsoft.AspNetCore.Authorization; |
| | 5 | | using Microsoft.AspNetCore.Mvc; |
| | 6 | | using Microsoft.IdentityModel.Tokens; |
| | 7 | | using WebApi.Models; |
| | 8 | | using WebApi.Services; |
| | 9 | |
|
| | 10 | | [ApiController] |
| | 11 | | [Route("[controller]")] |
| | 12 | | public class AuthController : ControllerBase |
| | 13 | | { |
| | 14 | | private readonly IConfiguration config; |
| | 15 | | private readonly IUserService _userService; |
| | 16 | |
|
| 3 | 17 | | public AuthController(IConfiguration config, IUserService userService) |
| 3 | 18 | | { |
| 3 | 19 | | this.config = config; |
| 3 | 20 | | this._userService = userService; |
| 3 | 21 | | } |
| | 22 | |
|
| | 23 | | private List<Claim> GenerateClaims(User user) |
| 2 | 24 | | { |
| 2 | 25 | | var claims = new[] |
| 2 | 26 | | { |
| 2 | 27 | | new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]), |
| 2 | 28 | | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| 2 | 29 | | new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()), |
| 2 | 30 | | new Claim(ClaimTypes.Name, user.Username), |
| 2 | 31 | | new Claim(ClaimTypes.Role, user.Role), |
| 2 | 32 | | new Claim("Email", user.Email), |
| 2 | 33 | | new Claim("Age", user.Age.ToString()), |
| 2 | 34 | | }; |
| 2 | 35 | | return claims.ToList(); |
| 2 | 36 | | } |
| | 37 | |
|
| | 38 | | private string GenerateJwt(User user) |
| 2 | 39 | | { |
| 2 | 40 | | List<Claim> claims = GenerateClaims(user); |
| | 41 | |
|
| 2 | 42 | | SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"])); |
| 2 | 43 | | SigningCredentials signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha512); |
| | 44 | |
|
| 2 | 45 | | JwtHeader header = new JwtHeader(signIn); |
| | 46 | |
|
| 2 | 47 | | JwtPayload payload = new JwtPayload( |
| 2 | 48 | | config["Jwt:Issuer"], |
| 2 | 49 | | config["Jwt:Audience"], |
| 2 | 50 | | claims, |
| 2 | 51 | | null, |
| 2 | 52 | | DateTime.UtcNow.AddMinutes(60)); |
| | 53 | |
|
| 2 | 54 | | JwtSecurityToken token = new JwtSecurityToken(header, payload); |
| | 55 | |
|
| 2 | 56 | | string serializedToken = new JwtSecurityTokenHandler().WriteToken(token); |
| 2 | 57 | | return serializedToken; |
| 2 | 58 | | } |
| | 59 | |
|
| | 60 | | [HttpPost, Route("login")] |
| | 61 | | public async Task<ActionResult> LoginAsync([FromBody] UserLoginDTO userLoginDto) |
| 3 | 62 | | { |
| | 63 | | try |
| 3 | 64 | | { |
| 3 | 65 | | User user = await _userService.ValidateUserAsync(userLoginDto.Username, userLoginDto.Password); |
| 2 | 66 | | string token = GenerateJwt(user); |
| | 67 | |
|
| 2 | 68 | | return Ok(token); |
| | 69 | | } |
| 1 | 70 | | catch (Exception e) |
| 1 | 71 | | { |
| 1 | 72 | | return BadRequest(e.Message); |
| | 73 | | } |
| 3 | 74 | | } |
| | 75 | |
|
| | 76 | | } |