Created
May 28, 2020 13:29
-
-
Save gavilanch/29f2157ffe301481e2001f7e546616c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Identity; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.IdentityModel.Tokens; | |
using System; | |
using System.Collections.Generic; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Linq; | |
using System.Security.Claims; | |
using System.Text; | |
using System.Threading.Tasks; | |
using WebApiModulo7.Models; | |
namespace WebApiModulo7.Controllers | |
{ | |
[Route("api/[controller]")] | |
[ApiController] | |
public class CuentasController : ControllerBase | |
{ | |
private readonly UserManager<ApplicationUser> _userManager; | |
private readonly SignInManager<ApplicationUser> _signInManager; | |
private readonly IConfiguration _configuration; | |
public CuentasController( | |
UserManager<ApplicationUser> userManager, | |
SignInManager<ApplicationUser> signInManager, | |
IConfiguration configuration) | |
{ | |
_userManager = userManager; | |
_signInManager = signInManager; | |
_configuration = configuration; | |
} | |
[HttpPost("Crear")] | |
public async Task<ActionResult<UserToken>> CreateUser([FromBody] UserInfo model) | |
{ | |
var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; | |
var result = await _userManager.CreateAsync(user, model.Password); | |
if (result.Succeeded) | |
{ | |
return BuildToken(user, new List<string>()); | |
} | |
else | |
{ | |
return BadRequest("Username or password invalid"); | |
} | |
} | |
[HttpPost("Login")] | |
public async Task<ActionResult<UserToken>> Login([FromBody] UserInfo userInfo) | |
{ | |
var result = await _signInManager.PasswordSignInAsync(userInfo.Email, userInfo.Password, isPersistent: false, lockoutOnFailure: false); | |
if (result.Succeeded) | |
{ | |
var usuario = await _userManager.FindByEmailAsync(userInfo.Email); | |
var roles = await _userManager.GetRolesAsync(usuario); | |
return BuildToken(usuario, roles); | |
} | |
else | |
{ | |
ModelState.AddModelError(string.Empty, "Invalid login attempt."); | |
return BadRequest(ModelState); | |
} | |
} | |
private UserToken BuildToken(ApplicationUser user, IList<string> roles) | |
{ | |
var claims = new List<Claim> | |
{ | |
new Claim(JwtRegisteredClaimNames.UniqueName, user.Email), | |
new Claim(ClaimTypes.NameIdentifier, user.Id), | |
new Claim("miValor", "Lo que yo quiera"), | |
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) | |
}; | |
foreach (var rol in roles) | |
{ | |
claims.Add(new Claim(ClaimTypes.Role, rol)); | |
} | |
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"])); | |
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | |
// Tiempo de expiración del token. En nuestro caso lo hacemos de una hora. | |
var expiration = DateTime.UtcNow.AddYears(1); | |
JwtSecurityToken token = new JwtSecurityToken( | |
issuer: null, | |
audience: null, | |
claims: claims, | |
expires: expiration, | |
signingCredentials: creds); | |
return new UserToken() | |
{ | |
Token = new JwtSecurityTokenHandler().WriteToken(token), | |
Expiration = expiration | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment