Ejemplo n.º 1
0
        public async Task <IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var user = new ApplicationUser
            {
                Email    = registerDto.Email,
                UserName = registerDto.Email,
                //Firstname = registerDto.Firstname,
                //Lastname = registerDto.Lastname
            };

            var userExists = await userManager.FindByEmailAsync(registerDto.Email);

            if (userExists != null)
            {
                return(Conflict());
            }

            var created = await userManager.CreateAsync(user, registerDto.Password);

            if (!created.Succeeded)
            {
                return(BadRequest());
            }
            var roles        = new List <string>();
            var token        = authService.GenerateToken(user, roles);
            var refreshToken = authService.GenerateRefreshToken(token);
            //user.RefreshToken = refreshToken;
            var isUpdated = await userManager.UpdateAsync(user);

            if (!isUpdated.Succeeded)
            {
                return(StatusCode(500));
            }

            var response = new TokenWithRefresh()
            {
                AccessToken  = token,
                RefreshToken = refreshToken.Token
            };

            return(Ok(response));
        }
        public async Task <IActionResult> GetAccessToken([FromBody] TokenWithRefresh tokens)
        {
            var principal = authService.GetClaimsFromToken(tokens.AccessToken, false);
            var userId    = principal.Claims.SingleOrDefault(x => x.Type == nameof(ApplicationUser.Id)).Value;
            var jti       = principal.Claims.SingleOrDefault(x => x.Type == JwtRegisteredClaimNames.Jti).Value;
            var user      = await userManager.FindByIdAsync(userId);

            var userRoles = await userManager.GetRolesAsync(user);

            var isValid = true;

            //(tokens.RefreshToken == user.RefreshToken.Token) &&
            //    (!user.RefreshToken.IsRevoked) &&
            //    (!user.RefreshToken.IsExpired);
            //&&(user.RefreshToken.Jti == jti);
            if (!isValid)
            {
                return(Unauthorized());
            }
            var newAccessToken = authService.GenerateToken(user, userRoles);

            return(Ok(newAccessToken));
        }