public async Task <IActionResult> AcquireToken(string resource) { if (_authOptions.UseAadB2c) { return(BadRequest("AAD B2C does not support on-behalf-of flow.")); } try { var claim = this.HttpContext.User.Claims.First(c => c.Type.Equals("access_token")); if (null == claim) { return(Ok(string.Empty)); } // Get the access token var token = claim.Value; var assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer"; var user = this.HttpContext.User; string userName = user.FindFirstValue(ClaimTypes.Upn) ?? user.FindFirstValue(ClaimTypes.Email); var userAssertion = new UserAssertion(token, assertionType, userName); var tokenCache = new MemoryTokenCache(userName, resource); var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{_authOptions.Tenant}", tokenCache); var clientCredential = new ClientCredential(_authOptions.ClientId, _authOptions.ClientSecret); var result = await authContext.AcquireTokenAsync(resource, clientCredential, userAssertion); return(Ok(result.AccessToken)); } catch (Exception e) { _logger.LogError(e, "Failed to acquire token."); throw; } }
public async Task GetToken() { var tenantId = TestEnvironment.ServicePrincipalTenantId; var clientId = TestEnvironment.ServicePrincipalClientId; var secret = TestEnvironment.ServicePrincipalClientSecret; var cache = new MemoryTokenCache(); var options = InstrumentClientOptions(new ClientSecretCredentialOptions() { TokenCachePersistenceOptions = cache }); var credential = InstrumentClient(new ClientSecretCredential(tenantId, clientId, secret, options)); var tokenRequestContext = new TokenRequestContext(new[] { AzureAuthorityHosts.GetDefaultScope(new Uri(TestEnvironment.AuthorityHostUrl)) }); // ensure we can initially acquire a token AccessToken token = await credential.GetTokenAsync(tokenRequestContext); Assert.IsNotNull(token.Token); Assert.That(cache.CacheReadCount, Is.Not.Zero); Assert.That(cache.CacheUpdatedCount, Is.Not.Zero); // ensure subsequent calls before the token expires are served from the token cache AccessToken cachedToken = await credential.GetTokenAsync(tokenRequestContext); Assert.AreEqual(token.Token, cachedToken.Token); var options2 = InstrumentClientOptions(new ClientSecretCredentialOptions()); // ensure new credentials don't share tokens from the cache var credential2 = new ClientSecretCredential(tenantId, clientId, secret, options2); AccessToken token2 = await credential2.GetTokenAsync(tokenRequestContext); if (Mode != RecordedTestMode.Playback && Mode != RecordedTestMode.None) { Assert.AreNotEqual(token.Token, token2.Token); } }
public async Task <string> AcquireToken(string resource) { try { var claim = this.HttpContext.User.Claims.First(c => c.Type.Equals("access_token")); if (null == claim) { return(string.Empty); } // Get the access token var token = claim.Value; //We are passing an *assertion* to Azure AD about the current user //Here we specify that assertion's type, that is a JWT Bearer token var assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer"; //User name is needed here only for ADAL, it is not passed to AAD //ADAL uses it to find a token in the cache if available var user = this.HttpContext.User; string userName = user.FindFirstValue(ClaimTypes.Upn) ?? user.FindFirstValue(ClaimTypes.Email); var userAssertion = new UserAssertion(token, assertionType, userName); var tokenCache = new MemoryTokenCache(userName, resource); var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{_authOptions.Tenant}", tokenCache); var clientCredential = new ClientCredential(_authOptions.ClientId, _authOptions.ClientSecret); var result = await authContext.AcquireTokenAsync(resource, clientCredential, userAssertion); return(result.AccessToken); } catch (Exception e) { _logger.LogError(e, "Failed to acquire token."); throw; } }