using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Text; using System.Security.Claims; using IdentityAPI.Models; using IdentityAPI.DTOs; namespace IdentityAPI.Controllers { [Route("api/users")] [ApiController] public class UsersController : ControllerBase { private readonly ApplicationDbContext _context; private readonly IConfiguration _configuration; private readonly UserManager _manager; public UsersController(ApplicationDbContext context, IConfiguration configuration, UserManager manager) { _context = context; _configuration = configuration; _manager = manager; } [HttpPost("signup")] public async Task SignUp(UserDTO data) { var user = new IdentityUser { UserName = data.UserName, Email = data.Email }; var result = await _manager.CreateAsync(user, data.Password); if(result.Succeeded) return Ok(new { Token = GenerateToken(user) }); return StatusCode(422, new { error = "The provided user is invalid" }); } [HttpPost("login")] public async Task Login(LoginRequest data) { if(data != null && data.Email != null && data.Password != null) { var user = await _manager.FindByEmailAsync(data.Email); if(user == null) return StatusCode(404, new { error = "Nonexistent user" }); var result = await _manager.CheckPasswordAsync(user, data.Password); if(result) return Ok(new { Token = GenerateToken(user)} ); return StatusCode(401, new { error = "Wrong credentials" }); } return StatusCode(400, new { error = "Invalid request body" }); } [HttpGet("refresh")] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public async Task Refresh() { var user = await _manager.FindByEmailAsync(HttpContext.User.Claims.Where(c => c.Type.Contains("email")).FirstOrDefault().Value); return Ok(new { Token = GenerateToken(user) }); } private string GenerateToken(IdentityUser user) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expiration = DateTime.UtcNow.AddMinutes(30); //var issuer = _configuration["Jwt:Issuer"]; var claims = new List { new Claim("sid", user.Id), new Claim("username", user.UserName), new Claim("email", user.Email) }; var descriptor = new JwtSecurityToken(issuer: null, audience: null, claims: claims, expires: expiration, signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(descriptor); } } }