private async Task <string> GenerateJwtRefreshTokenAsync(User user) { var refreshTokenKey = Guid.NewGuid().ToString().Replace("-", ""); var usertoken = new UserToken() { UserId = user.Id, RefreshTokenKey = refreshTokenKey }; var savetoDb = await _userTokenRepository.AddAsync(usertoken); if (savetoDb <= 0) { throw new Exception("audience"); } var refreshSceretKey = _jwtSettings.Value.RefreshSecretKey; //TODO: get from appSetting.json IdentityOptions options = new IdentityOptions(); var key = Encoding.ASCII.GetBytes(refreshSceretKey); var claims = new List <Claim>() { // Claim Type = Name is UserId new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(options.ClaimsIdentity.UserIdClaimType, user.Id.ToString(), ClaimValueTypes.String), new Claim(options.ClaimsIdentity.UserNameClaimType, user.UserName, ClaimValueTypes.String), new Claim(JWTInfor.RefreshTokenKey, refreshTokenKey, ClaimValueTypes.String) }; var jwt = new JwtSecurityToken( issuer: _jwtSettings.Value.Issuer, audience: _jwtSettings.Value.Audience, claims: claims, notBefore: usertoken.CreationTime, expires: DateTime.UtcNow.AddMinutes(_jwtSettings.Value.RefreshTokenValidFor), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)); var refreshToken = new JwtSecurityTokenHandler().WriteToken(jwt); return(refreshToken); }
public async Task <AccessToken> CreateAccessTokenAsync(User user) { try { var refreshToken = BuildRefreshToken(user); var accessToken = BuildAccessToken(user, refreshToken); // _refreshTokens.Add(refreshToken); UserToken userToken = new UserToken { RefreshToken = refreshToken.Token, Email = user.Email, Expiration = refreshToken.Expiration, AccessToken = "" }; await _userTokenRepository.AddAsync(userToken); await _unitOfWork.CompleteAsync(); return(accessToken); } catch (Exception ex) { _logService.LogException(ex, "CreateAccessTokenAsync"); return(null); } }