|
| 1 | +using Microsoft.AspNetCore.Identity; |
| 2 | +using Microsoft.AspNetCore.Mvc; |
| 3 | +using System.Security.Cryptography; |
| 4 | + |
| 5 | +namespace BAuth.Controllers |
| 6 | +{ |
| 7 | + [ApiController] |
| 8 | + [Route("api/[controller]")] |
| 9 | + public class AuthController : Controller |
| 10 | + { |
| 11 | + public static User user = new User(); |
| 12 | + [HttpPost("register")] |
| 13 | + public async Task<ActionResult<User>> Register(UserDto request) |
| 14 | + { |
| 15 | + CreatePasswordHash(request.Password,out byte[] passwordHash,out byte[] passwordSalt); |
| 16 | + user.Name = request.Name; |
| 17 | + user.PasswordSalt = passwordSalt; |
| 18 | + user.PasswordHash = passwordHash; |
| 19 | + return Ok(user); |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + [HttpPost("login")] |
| 24 | + public async Task<ActionResult<User>> LogIn(UserDto request) |
| 25 | + { |
| 26 | + if(user.Name != request.Name) |
| 27 | + { |
| 28 | + return BadRequest("User not found!"); |
| 29 | + } |
| 30 | + if(!VerifyPassword(request.Password, user.PasswordHash,user.PasswordSalt)) |
| 31 | + { |
| 32 | + return BadRequest("Wrong password!"); |
| 33 | + } |
| 34 | + var token = CreateToken() |
| 35 | + return Ok(token); |
| 36 | + } |
| 37 | + |
| 38 | + private void CreatePasswordHash(string password, out byte[]passwordHash, out byte[]PasswordSalt) |
| 39 | + { |
| 40 | + using (var hmac = new HMACSHA256()) |
| 41 | + { |
| 42 | + PasswordSalt = hmac.Key; |
| 43 | + passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); |
| 44 | + } |
| 45 | + } |
| 46 | + private bool VerifyPassword(string password, out byte[]passwordHash, out byte[]PasswordSalt) |
| 47 | + { |
| 48 | + using (var hmac = new HMACSHA256(PasswordSalt)) |
| 49 | + { |
| 50 | + var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); |
| 51 | + return computedHash.SequenceEqual(passwordHash); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + |
| 56 | + } |
| 57 | +} |
0 commit comments