public IActionResult auth(AuthenticationRequest req) { try { if (req.grant_type == "refresh_token") { var tokenData = _refreshTokenProvider.FetchToken(req.refresh_token); var user = _authenticator.FetchUser(req, tokenData.UserID); var jwt = TokenGenerator.GenerateToken(user.Claims, req.security_provider ?? _defaultSecurityProvider); var refreshTokenString = _refreshTokenProvider.RefreshToken(tokenData, IpAddress()).Token; var res = new AuthenticationResponse { token = jwt, refresh_token = refreshTokenString }; return(Ok(res)); } else if (req.grant_type == null || req.grant_type == "password") { var user = _authenticator.Authenticate(req); var jwt = TokenGenerator.GenerateToken(user.Claims, req.security_provider ?? _defaultSecurityProvider); var refreshTokenString = _refreshTokenProvider.GenerateRefreshToken(user.UserId, IpAddress()).Token; var res = new AuthenticationResponse { token = jwt, refresh_token = refreshTokenString }; return(Ok(res)); } return(BadRequest("grant_type no soportado")); } catch (AuthorizationException e) { return(Unauthorized(e.Message)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
private async Task<JsonWebToken> GenerateAccessAndRefreshTokenAsync(User user) { var claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), }; //var roles = await _userManager.GetRolesAsync(user); //if (roles != null) //{ // claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); //} //Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var refreshToken = _refreshTokenProvider.GenerateRefreshToken(user.Id, user.Email); await _refreshTokenProvider.SaveRefreshTokenAsync(user.Id, user.Email, refreshToken); var jsonWebToken = new JsonWebToken { AccessToken = encodedJwt, RefreshToken = refreshToken, ExpiresIn = _jwtOptions.Expiration, User = new JsonWebTokenUser { FirstName = user.Login, LastName = user.Email, //Roles = roles?.ToList(), Id = user.Id } }; return jsonWebToken; }