/// <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); }
public bool HasPrincipalRefreshToken(BearerSignInManagerContext <UserType, BearerTokenType> context) { var principal = context.Principal ?? throw BearerSignInManagerThrowHelper.GetContextArgumentException(nameof(BearerSignInManagerContext <UserType, BearerTokenType> .Principal)); var hasRefreshTokenId = Guid.TryParse(principal.FindFirstValue(BearerSignInManagerDefaults.SignInServiceRefreshTokenIdClaimType), out _); if (!hasRefreshTokenId) { context.SetResult() .ToFailure("The refresh token is not valid.") .WithHttpStatusCode(HttpStatusCode.Unauthorized); return(false); } return(true); }