private async Task LoadAuthenticationTicketAsync(CancellationToken cancellationToken) { var authorizationResult = await this.authorizationClient.AuthorizeWithPkceAsync(cancellationToken).ConfigureAwait(false); var tokens = await this.tokenClient.GetTokensFromAuthorizationResultAsync( authorizationResult.AuthorizationCode, authorizationResult.CodeVerifier, authorizationResult.RedirectUri, cancellationToken).ConfigureAwait(false); var user = await this.userClient.GetCurrentUserAsync(tokens.AccessToken, cancellationToken).ConfigureAwait(false); var options = this.optionsProvider.Get(); var claimsFromResolvers = options.UserClaimResolvers .Select(r => (r.ClaimType, ClaimValue: r.Resolver(user))) .Where(c => !string.IsNullOrEmpty(c.ClaimValue)) .Select(c => new UserClaim(c.ClaimType, c.ClaimValue)) .ToList(); var userClaims = new UserClaims(claimsFromResolvers); if (!userClaims.HasClaim(UserClaimTypes.Id)) { throw new InvalidOperationException("User was ID not found. Ensure that Id claim is added via SpotifyAuthorizationCodeFlowOptions."); } var result = new AuthenticationTicket( tokens.RefreshToken, tokens.GetAccessTokenModel(this.clock), userClaims); await this.authenticationTicketRepository.SaveAsync(result, cancellationToken).ConfigureAwait(false); this.UpdateAuthenticationTicketSafe(result); }
private AuthenticationTicket GetAuthenticationTicketFromJsonElement(JsonElement element, int version) { switch (version) { case Version: var repositoryItem = this.ToObject <AuthenticationTicketRepositoryItem>(element); if (repositoryItem == null) { throw new SpotifyMalformedAuthenticationTicketException("Unable to get authentication ticket."); } if (string.IsNullOrEmpty(repositoryItem.RefreshToken) || string.IsNullOrEmpty(repositoryItem.AccessToken) || repositoryItem.ExpiresAt == null) { throw new SpotifyMalformedAuthenticationTicketException("Unable to get authentication tokens."); } if (repositoryItem.UserClaims?.Any(kvp => string.IsNullOrEmpty(kvp.Key) || string.IsNullOrEmpty(kvp.Value)) == true) { throw new SpotifyMalformedAuthenticationTicketException("Unable to get user claims."); } var userClaims = new UserClaims(repositoryItem.UserClaims?.Select(kvp => new UserClaim(kvp.Key, kvp.Value))); if (!userClaims.HasClaim(UserClaimTypes.Id)) { throw new SpotifyMalformedAuthenticationTicketException("Unable to get User ID."); } return(new AuthenticationTicket( repositoryItem.RefreshToken, new AccessToken(repositoryItem.AccessToken, repositoryItem.ExpiresAt.Value), userClaims)); default: throw new SpotifyMalformedAuthenticationTicketException($"Stored authentication ticket has version {version} that is not supported."); } }