/// <inheritdoc/> public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) { AuthenticationResult result = _tokenAcquisition.GetAuthenticationResultForUserAsync(requestContext.Scopes) .GetAwaiter() .GetResult(); return(new AccessToken(result.AccessToken, result.ExpiresOn)); }
public async Task <ActionResult <string> > CallProtectedEndPoint() { var authResult = await tokenAcquisition.GetAuthenticationResultForUserAsync(new string[] { configuration["AzureAdB2C:WebApi1Scope"] }); var idToken = authResult.IdToken; //just a check to see we have an id token var accessToken = authResult.AccessToken; //access token is null //also returns a null access token var accessToken2 = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] { configuration["AzureAdB2C:WebApi1Scope"] }); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await httpClient.GetAsync("Test/GetProtected"); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } else { return(response.StatusCode.ToString()); } }
/// <summary> /// This methods the processing of user data where the web API periodically checks the user /// date (think of OneDrive producing albums) /// </summary> private async Task RegisterPeriodicCallbackForLongProcessing(string keyHint) { // Get the token incoming to the web API - we could do better here. TokenAcquisitionOptions tokenAcquisitionOptions = new TokenAcquisitionOptions() { LongRunningWebApiSessionKey = keyHint ?? TokenAcquisitionOptions.LongRunningWebApiSessionKeyAuto }; _ = await _tokenAcquisition.GetAuthenticationResultForUserAsync(new string[] { "user.read" }, tokenAcquisitionOptions : tokenAcquisitionOptions); string key = tokenAcquisitionOptions.LongRunningWebApiSessionKey; // Build the URL to the callback controller, based on the request. var request = HttpContext.Request; string endpointPath = request.Path.Value.Replace("todolist", "callback", StringComparison.OrdinalIgnoreCase); string url = $"{request.Scheme}://{request.Host}{endpointPath}?key={key}"; // Setup a timer so that the API calls back the callback every 10 mins. Timer timer = new Timer(async(state) => { HttpClient httpClient = new HttpClient(); var message = await httpClient.GetAsync(url); }, null, 1000, 1000 * 60 * 1); // Callback every minute }
/// <inheritdoc/> public async Task <HttpResponseMessage> CallWebApiForUserAsync( string serviceName, string?authenticationScheme = null, Action <DownstreamWebApiOptions>?calledDownstreamWebApiOptionsOverride = null, ClaimsPrincipal?user = null, StringContent?content = null) { DownstreamWebApiOptions effectiveOptions = MergeOptions(serviceName, calledDownstreamWebApiOptionsOverride); if (string.IsNullOrEmpty(effectiveOptions.Scopes)) { throw new ArgumentException(IDWebErrorMessage.ScopesNotConfiguredInConfigurationOrViaDelegate); } MicrosoftIdentityOptions microsoftIdentityOptions = _microsoftIdentityOptionsMonitor .Get(_tokenAcquisition.GetEffectiveAuthenticationScheme(authenticationScheme)); string apiUrl = effectiveOptions.GetApiUrl(); CreateProofOfPossessionConfiguration(effectiveOptions, apiUrl); string?userflow; if (microsoftIdentityOptions.IsB2C && string.IsNullOrEmpty(effectiveOptions.UserFlow)) { userflow = microsoftIdentityOptions.DefaultUserFlow; } else { userflow = effectiveOptions.UserFlow; } AuthenticationResult authResult = await _tokenAcquisition.GetAuthenticationResultForUserAsync( effectiveOptions.GetScopes(), authenticationScheme, effectiveOptions.Tenant, userflow, user, effectiveOptions.TokenAcquisitionOptions) .ConfigureAwait(false); using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage( effectiveOptions.HttpMethod, apiUrl)) { if (content != null) { httpRequestMessage.Content = content; } httpRequestMessage.Headers.Add( Constants.Authorization, authResult.CreateAuthorizationHeader()); effectiveOptions.CustomizeHttpRequestMessage?.Invoke(httpRequestMessage); return(await _httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false)); } }
public override async ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) { // requestContext.Scopes "https://storage.azure.com/.default" string[] scopes = _configuration["AzureStorage:ScopeForAccessToken"]?.Split(' '); AuthenticationResult result = await _tokenAcquisition .GetAuthenticationResultForUserAsync(scopes) .ConfigureAwait(false); return(new AccessToken(result.AccessToken, result.ExpiresOn)); }
public async Task GetAsync(string key) { var request = HttpContext.Request; string calledUrl = request.Scheme + "://" + request.Host + request.Path.Value + Request.QueryString; _logger.LogWarning($"{DateTime.UtcNow}: {calledUrl}"); TokenAcquisitionOptions tokenAcquisitionOptions = new TokenAcquisitionOptions() { LongRunningWebApiSessionKey = key }; var result = await _tokenAcquisition.GetAuthenticationResultForUserAsync( new string[] { "user.read" }, tokenAcquisitionOptions : tokenAcquisitionOptions) .ConfigureAwait(false); // for testing OBO _logger.LogWarning($"OBO token acquired from {result.AuthenticationResultMetadata.TokenSource} expires {result.ExpiresOn.UtcDateTime}"); // For breakpoint if (result.AuthenticationResultMetadata.TokenSource == Microsoft.Identity.Client.TokenSource.IdentityProvider) { } }