public static async Task <string> GetUserToken(string userId) { var confidentialClient = new ConfidentialClientApplication(notifAppId, authority, redirectUri, notifClientCreds, BlobTokenCache.GetMsalCacheInstance(), null); //Logger.LogCallback = AuthLog; //Logger.Level = Microsoft.Identity.Client.LogLevel.Verbose; //Logger.PiiLoggingEnabled = true; var account = await confidentialClient.GetAccountAsync($"{userId}.{tid}"); if (account == null) { return(string.Empty); } try { var result = await confidentialClient.AcquireTokenSilentAsync(notifScopes, account); return(result.AccessToken); } catch (MsalException) { return(string.Empty); } }
private async Task <string> GetUserAccessTokenAsync(IEnumerable <string> scopes) { var userId = this.GetUserObjectId(); var appSecret = await this.keyVaultService.GetSecret(this.config.AppSecretKeyVaultKey); var credential = new ClientCredential(appSecret); var request = this.httpContextAccessor.HttpContext.Request; var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase); var tokenCache = new DistributedTokenCacheHelper(this.cache, this.dataProtectionProvider, userId).GetTokenCache(); var application = new ConfidentialClientApplication(this.config.ClientId, this.config.Authority, currentUri, credential, tokenCache, null); AuthenticationResult result; try { IAccount account = await application.GetAccountAsync($"{userId}.{this.config.TenantId}"); result = await application.AcquireTokenSilentAsync(scopes, account); } catch { var token = await this.httpContextAccessor.HttpContext.GetTokenAsync("access_token"); var userAssertion = new UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer"); result = await application.AcquireTokenOnBehalfOfAsync(scopes, userAssertion); } return(result.AccessToken); }
public async Task <string> GetUserAccessTokenAsync(string userId, string userTenant) { _tokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance(); var confidentialClientApplication = new ConfidentialClientApplication(_appId, _redirectUri, _credential, _tokenCache, null); //var account = await confidentialClientApplication.GetAccountsAsync("446985bc-8939-42d8-8fbc-962f84527b57.99360fd3-03fe-4f03-9291-fe0c7db80be3"); var account = await confidentialClientApplication.GetAccountAsync($"{userId}.{userTenant}"); //var c = account.First(); var result = await confidentialClientApplication.AcquireTokenSilentAsync(_scopes, account); return(result.AccessToken); }
private static async Task RunAuthCode_Async(MockHttpManager httpManager, ConfidentialClientApplication app) { httpManager.AddSuccessTokenResponseMockHandlerForPost(); var result = await app .AcquireTokenByAuthorizationCode(TestConstants.s_scope, "some-code") .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource); var acc = await app.GetAccountAsync(result.Account.HomeAccountId.Identifier).ConfigureAwait(false); result = await app.AcquireTokenSilent(TestConstants.s_scope, acc).ExecuteAsync().ConfigureAwait(false); Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource); }
/// <summary> /// Gets an access token for a downstream API on behalf of the user which account ID is passed as an argument /// </summary> /// <param name="accountIdentifier">User account identifier for which to acquire a token. /// See <see cref="Microsoft.Identity.Client.AccountId.Identifier"/></param> /// <param name="scopes">Scopes for the downstream API to call</param> private async Task <string> GetAccessTokenOnBehalfOfUser(ConfidentialClientApplication application, string accountIdentifier, IEnumerable <string> scopes, string loginHint) { if (accountIdentifier == null) { throw new ArgumentNullException(nameof(accountIdentifier)); } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } // Get the account IAccount account = await application.GetAccountAsync(accountIdentifier); // Special case for guest users as the Guest iod / tenant id are not surfaced. if (account == null) { var accounts = await application.GetAccountsAsync(); account = accounts.FirstOrDefault(a => a.Username == loginHint); } try { AuthenticationResult result = null; result = await application.AcquireTokenSilentAsync(scopes.Except(scopesRequestedByMsalNet), account); return(result.AccessToken); } catch (MsalException) { // TODO process the exception see if this is retryable etc ... throw; } }
/// <summary> /// Gets an access token for a downstream API on behalf of the user which account ID is passed as an argument /// </summary> /// <param name="accountIdentifier">User account identifier for which to acquire a token. /// See <see cref="Microsoft.Identity.Client.AccountId.Identifier"/></param> /// <param name="scopes">Scopes for the downstream API to call</param> private async Task <string> GetAccessTokenOnBehalfOfUser(HttpContext httpContext, ConfidentialClientApplication application, string accountIdentifier, IEnumerable <string> scopes) { if (accountIdentifier == null) { throw new ArgumentNullException(nameof(accountIdentifier)); } if (scopes == null) { throw new ArgumentNullException(nameof(scopes)); } var accounts = await application.GetAccountsAsync(); try { AuthenticationResult result = null; var allAccounts = await application.GetAccountsAsync(); IAccount account = await application.GetAccountAsync(accountIdentifier); result = await application.AcquireTokenSilentAsync(scopes.Except(_scopesRequestedByMsalNet), account); return(result.AccessToken); } catch (MsalUiRequiredException ex) { ReplyForbiddenWithWwwAuthenticateHeader(httpContext, scopes, ex); return(null); } catch (MsalException ex) { // TODO process the exception see if this is retryable etc ... throw; } }