From 995e5918b887a248803152aa8f36fdbfa5659baf Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Mon, 14 Nov 2022 23:31:32 -0600 Subject: AƱadido registro de usuarios y configuraciĆ³n de JWTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/UsersController.cs | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Controllers/UsersController.cs (limited to 'Controllers/UsersController.cs') diff --git a/Controllers/UsersController.cs b/Controllers/UsersController.cs new file mode 100644 index 0000000..52c9105 --- /dev/null +++ b/Controllers/UsersController.cs @@ -0,0 +1,53 @@ +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.DTO; + +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 PostUser(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" }); + } + + 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); + } + } +} -- cgit v1.2.3