/// <summary> /// The access token does contain user user id, user name and user roles. /// </summary> protected virtual async Task <bool> TrySetContextAccessTokenAsync(BearerSignInManagerContext <UserType, BearerTokenType> context) { var user = context.User ?? throw BearerSignInManagerThrowHelper.GetContextArgumentException(nameof(context.User)); var accessTokenDescriptor = signInManagerOptions.CreateAccessTokenDescriptor(); // Used by authentication middleware. accessTokenDescriptor.Claims.Add(ClaimTypes.NameIdentifier, user.Id); accessTokenDescriptor.Claims.Add(ClaimTypes.Name, user.UserName); try { var roles = await userManager.GetRolesAsync(user); if (roles != null) { foreach (var role in roles) { accessTokenDescriptor.Claims.Add(ClaimTypes.Role, role); } } context.AccessToken = BearerSignInManagerTools.GenerateJwtToken(accessTokenDescriptor, signInManagerOptions.SetDefaultTimesOnTokenCreation); return(true); } catch (Exception error) { context.SetResult(errorDetailsProvider.LogCriticalThenBuildAppropiateError <object>(error, "The access token could not be created.") .WithHttpStatusCode(HttpStatusCode.InternalServerError)); } return(false); }
/// <summary> /// The refresh token does contain user security stamp and refresh token id. /// </summary> protected virtual async Task <bool> TrySetContextRefreshTokenEntityAsync(BearerSignInManagerContext <UserType, BearerTokenType> context) { var user = context.User ?? throw new ArgumentNullException(nameof(BearerSignInManagerContext <UserType, BearerTokenType> .User)); var refreshTokenDescriptor = signInManagerOptions.CreateRefreshTokenDescriptor(); var issuedAtUtc = refreshTokenDescriptor.IssuedAt == null ? DateTime.UtcNow : DateTime.SpecifyKind((DateTime)refreshTokenDescriptor.IssuedAt, DateTimeKind.Utc); var expiresAtUtc = refreshTokenDescriptor.Expires ?? throw new ArgumentNullException(nameof(refreshTokenDescriptor.Expires)); var refreshTokenEntity = CreateRefreshToken(user.Id, issuedAtUtc, expiresAtUtc); var hasStorageSucceeded = await TryStoreRefreshTokenEntityAsync(context, refreshTokenEntity); if (hasStorageSucceeded) { refreshTokenDescriptor.Claims.Add(identityOptions.Value.ClaimsIdentity.SecurityStampClaimType, user.SecurityStamp); refreshTokenDescriptor.Claims.Add(BearerSignInManagerDefaults.SignInServiceRefreshTokenIdClaimType, refreshTokenEntity.BearerTokenId); var refreshToken = BearerSignInManagerTools.GenerateJwtToken(refreshTokenDescriptor, signInManagerOptions.SetDefaultTimesOnTokenCreation); context.RefreshTokenEntity = refreshTokenEntity; context.RefreshToken = refreshToken; return(true); } return(false); }