/// <summary> /// Gets the current authenticated user using JavaScript interop. /// </summary> /// <returns>A <see cref="Task{ClaimsPrincipal}"/>that will return the current authenticated user when completes.</returns> protected override async Task <ClaimsPrincipal> GetAuthenticatedUser() { var accessTokenResult = await RequestAccessToken(); if (accessTokenResult.Status == AccessTokenResultStatus.Success && accessTokenResult.TryGetToken(out var accessToken)) { using var userInfoClient = CreateClient(Client.Options); using var request = new UserInfoRequest { Address = Client.Options.ProviderInformation.UserInfoEndpoint, Token = accessToken.Value, }; var userInfoResponse = await userInfoClient.GetUserInfoAsync(request).ConfigureAwait(true); if (userInfoResponse.Exception != null) { throw userInfoResponse.Exception; } var account = JsonSerializer.Deserialize <TAccount>(userInfoResponse.Raw); await MergeIdTokenClaims(account); return(await AccountClaimsPrincipalFactory.CreateUserAsync(account, Options.UserOptions)); } else { return(new ClaimsPrincipal(new ClaimsIdentity())); } }
/// <summary> /// Gets the users and converts to into a <see cref="ClaimsPrincipal"/> /// </summary> /// <param name="useCache"></param> /// <returns></returns> protected async Task <ClaimsPrincipal> GetUser(bool useCache = false) { var now = DateTimeOffset.Now; if (useCache && now < _userLastCheck + _userCacheRefreshInterval) { return(_cachedUser); } try { var authenticatedUser = await GetAuthenticatedUser(); if (!ClaimsPrincipalEqualityComparer.Equals(_cachedUser, authenticatedUser)) { NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(authenticatedUser))); } _cachedUser = authenticatedUser; _userLastCheck = now; return(_cachedUser); } catch { // only throw when not using the cache (e.g. after a sign in or sign-out operation). if (!useCache) { throw; } else { // pass through the AccountClaimsPrincipalFactory to facilitate possible restore from storage. // this is equal to silent fail of the authentication in the javascript version where a user // is returned from javascript. var recreatedUser = await AccountClaimsPrincipalFactory.CreateUserAsync(null, Options.UserOptions); if (!ClaimsPrincipalEqualityComparer.Equals(_cachedUser, recreatedUser)) { NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(recreatedUser))); } _cachedUser = recreatedUser; _userLastCheck = now; return(_cachedUser); } } }