private async Task PrepareClient() { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _productReadScope }); Debug.WriteLine($"access token-{accessToken}"); _productClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); }
public async Task <IActionResult> Index() { string[] scopes = new string[] { "user.read" }; string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); ViewBag.token = accessToken; return(View()); }
private async Task PrepareAuthenticatedClient() { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope }); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _apiAccessKey); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
private async Task PrepareAuthenticatedClient() { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope }); Debug.WriteLine($"access token-{accessToken}"); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
private Graph::GraphServiceClient GetGraphServiceClient(string[] scopes) { return(GraphServiceClientFactory.GetAuthenticatedGraphClient(async() => { string result = await tokenAcquisition.GetAccessTokenForUserAsync(scopes); return result; }, webOptions.GraphApiUrl)); }
public async Task <ActionResult> Index() { var client = new HttpClient(); var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(Constants.ProductCatalogAPI.SCOPES); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var json = await client.GetStringAsync(url); var serializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var categories = JsonSerializer.Deserialize(json, typeof(List <Category>), serializerOptions) as List <Category>; return(View(categories)); }
private GraphServiceClient GetGraphServiceClient(string[] scopes) { //Ask the Graph Factoy to create a GraphServiceAPI client. Using the token of the user that is logged in authorized return(GraphFactory.GetAuthenticatedGraphClient(async() => { //Uses project Microsoft.Identity.Web to get the token string result = await tokenAcquisition.GetAccessTokenForUserAsync(scopes); return result; }, webOptions.GraphApiUrl)); }
private async Task PrepareAuthenticatedClient(string userFlow) { // Each user flow is a separate authorization server. // specify which user flow is connected to the web API. var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope, }, userFlow : userFlow); Debug.WriteLine($"access token-{accessToken}"); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
public GraphClientAuthProvider(ITokenAcquisition token) { Token = token; var accessToken = token.GetAccessTokenForUserAsync(Scopes).GetAwaiter().GetResult(); AuthProvider = new DelegateAuthenticationProvider(x => { x.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return(Task.FromResult(0)); }); }
/// <summary> /// Adds a bearer header to an HttpRequestMessage. /// </summary> /// <param name="request">HttpRequest message to authenticate.</param> /// <returns>A Task (as this is an async method).</returns> public async Task AuthenticateRequestAsync(HttpRequestMessage request) { request.Headers.Add( Constants.Authorization, string.Format( CultureInfo.InvariantCulture, "{0}{1}", Constants.Bearer, await _tokenAcquisition.GetAccessTokenForUserAsync(_initialScopes).ConfigureAwait(false))); }
/// <inheritdoc/> public async Task <HttpResponseMessage> CallWebApiForUserAsync( string serviceName, 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); } string?userflow; if (_microsoftIdentityOptions.IsB2C && string.IsNullOrEmpty(effectiveOptions.UserFlow)) { userflow = _microsoftIdentityOptions.DefaultUserFlow; } else { userflow = effectiveOptions.UserFlow; } string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync( effectiveOptions.GetScopes(), effectiveOptions.Tenant, userflow, user, effectiveOptions.TokenAcquisitionOptions) .ConfigureAwait(false); HttpResponseMessage response; using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage( effectiveOptions.HttpMethod, effectiveOptions.GetApiUrl())) { if (content != null) { httpRequestMessage.Content = content; } httpRequestMessage.Headers.Add( Constants.Authorization, string.Format( CultureInfo.InvariantCulture, "{0} {1}", Constants.Bearer, accessToken)); response = await _httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false); } return(response); }
public void OnGet() { string[] scopes = new[] { "mail.read" }; GraphServiceClient graphClient = GraphServiceClientFactory.GetAuthenticatedGraphClient(async() => { string result = await tokenAcquisition.GetAccessTokenForUserAsync(scopes); return(result); }, "https://graph.microsoft.com/beta/"); Messages = graphClient.Me.Messages.Request().Top(10).GetAsync().Result; }
private async Task PrepareAuthenticatedClient() { //You would specify the scopes (delegated permissions) here for which you desire an Access token of this API from Azure AD. //Note that these scopes can be different from what you provided in startup.cs. //The scopes provided here can be different or more from the ones provided in Startup.cs. Note that if they are different, //then the user might be prompted to consent again. var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new List <string>()); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
private async Task <string> GetAccessTokenAsync() { try { return(await tokenAcquisition.GetAccessTokenForUserAsync(scopes)); } catch (MsalUiRequiredException) { throw new ReauthenticationRequiredException(); } }
public async Task <string> GetAccessToken(IEnumerable <string> scopeResources, int version, string accessToken = "") { if (version == 2) { return(await _tokenAcquisition.GetAccessTokenForUserAsync(scopeResources)); } var resouce = scopeResources.First(); var res = await _v1AuthContext.AcquireTokenAsync(resouce, _clientCredential, new UserAssertion(accessToken)); return(res.AccessToken); }
private async Task <PnPContext> createSiteContext() { var siteUrl = new Uri(_pnpCoreOptions.Sites["DemoSite"].SiteUrl); return(await _pnpContextFactory.CreateAsync(siteUrl, new ExternalAuthenticationProvider((resourceUri, scopes) => { return _tokenAcquisition.GetAccessTokenForUserAsync(scopes).GetAwaiter().GetResult(); } ))); }
public async Task OnGetAsync() { var client = _clientFactory.CreateClient(); var scope = _configuration["CallApi:ScopeForAccessToken"]; var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { scope }); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); RandomString = await client.GetStringAsync(_configuration["CallApi:FunctionsApiUrl"]); }
public async Task <IActionResult> Index() { string[] scopes = new string[] { "user.read", "https://storage.azure.com/user_impersonation" }; var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); TokenCredential tokenCredential = new TokenCredential(accessToken); StorageCredentials storageCredentials = new StorageCredentials(tokenCredential); CloudBlockBlob blob = new CloudBlockBlob(new Uri("https://storagegrp02no01.blob.core.windows.net/data/sample.txt"), storageCredentials); await blob.UploadTextAsync("This is a sample file"); return(View()); }
public async Task <IEnumerable <Todo> > GetAsync() { string owner = User.GetDisplayName(); // Below is for testing multi-tenants var result = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }).ConfigureAwait(false); // for testing OBO var result2 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read.all" }, tokenAcquisitionOptions : new TokenAcquisitionOptions { ForceRefresh = true }).ConfigureAwait(false); // for testing OBO await RegisterPeriodicCallbackForLongProcessing(null); // string token1 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }, "7f58f645-c190-4ce5-9de4-e2b7acd2a6ab").ConfigureAwait(false); // string token2 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }, "3ebb7dbb-24a5-4083-b60c-5a5977aabf3d").ConfigureAwait(false); await Task.FromResult(0); // fix CS1998 while the lines about the 2 tokens are commented out. return(TodoStore.Values.Where(x => x.Owner == owner)); }
public async Task <IActionResult> Index() { var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(request) => { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { "User.Read" }); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); })); var user = await graphServiceClient.Me.Request().GetAsync(); return(View(user)); }
private async Task <HttpRequestMessage> PrepareAuthenticatedClient( string url, HttpMethod httpMethod) { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope }); Debug.WriteLine($"access token-{accessToken}"); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, url); httpRequestMessage.Headers.Add("Authorization", $"bearer {accessToken}"); httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(httpRequestMessage); }
public async Task <Event> CallGraphApiOnBehalfOfUserForEvent(string eventId) { string[] scopes = { "user.read", "user.readbasic.all", "mail.send", "calendars.readwrite", "calendars.readwrite.shared", "user.read.all" }; // we use MSAL.NET to get a token to call the API On Behalf Of the current user try { string infernoAPIKey = _configuration.GetValue <string>("InfernoAPIKey"); //ClaimsIdentity claimsIdentity = HttpContext.User.Identity as ClaimsIdentity; string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); Event newEvent = await CallGraphApiOnBehalfOfUserForEvent(infernoAPIKey, eventId, accessToken /*, claimsIdentity*/); return(newEvent); } catch (MsalUiRequiredException ex) { await _tokenAcquisition.ReplyForbiddenWithWwwAuthenticateHeaderAsync(scopes, ex); throw ex; } }
/// <summary> /// retrieve the Auth Token for the current user /// </summary> /// <param name="apiGroupConfigurationName"></param> /// <returns></returns> public async Task <string> GetAccessToken(string apiGroupConfigurationName = "ApiUser") { try { return(await _tokenAcquisition.GetAccessTokenForUserAsync(new List <string>() { _configurationManager.GetValue($"AzureAdPermissions:{apiGroupConfigurationName}Scope") })); } catch //(Exception authenticationError) { //expected that this happens when the user login has expired but the identity is known, no need to log //_applicationLogTools.LogError(authenticationError, new Dictionary<string, dynamic> { { "ClassName", $"WebApi.ApiControllerBase" } }); return(null); } }
public async Task <IEnumerable <Todo> > GetAsync() { string owner = User.GetDisplayName(); // Below is for testing multi-tenants await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }).ConfigureAwait(false); // for testing OBO // string token1 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }, "7f58f645-c190-4ce5-9de4-e2b7acd2a6ab").ConfigureAwait(false); // string token2 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "user.read" }, "3ebb7dbb-24a5-4083-b60c-5a5977aabf3d").ConfigureAwait(false); await Task.FromResult(0); // fix CS1998 while the lines about the 2 tokens are commented out. return(TodoStore.Values.Where(x => x.Owner == owner)); }
private async Task <HttpClient> GetHttpClientAsync(string neededScope) { var client = _clientFactory.CreateClient(); var scope = _configuration.GetSection("Api:ScopesForAccessToken").GetValue <string>(neededScope); var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { scope }); client.BaseAddress = new Uri(_configuration["Api:ApiBaseAddress"]); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(client); }
private async Task <HttpClient> GetHttpClient() { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_tdesApiOption.Value.BaseUrl); string token = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { _tdesApiOption.Value.Scope }); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); return(client); }
public async Task <string> GetTokenOnBeHalfOfFlowAsync(IEnumerable <string> scopes) { try { var token = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); return(token); } catch (Exception e) { throw e; } }
public async Task <IActionResult> Embed() { // Generate token for the signed in user and store in cache await m_tokenAcquisition.GetAccessTokenForUserAsync(new string[] { PowerBiScopes.ReadDashboard, PowerBiScopes.ReadReport, PowerBiScopes.ReadWorkspace }); // Get username of logged in user var userInfo = await m_graphServiceClient.Me.Request().GetAsync(); var userName = userInfo.DisplayName; ViewData["username"] = userName; return(View()); }
private async Task <string> GetAccessToken(string[] scopes) { try { return(await tokenAcquisition.GetAccessTokenForUserAsync(scopes)); } catch (Exception ex) { //Triggers a challenge if the token is not found or has expired. handler.HandleException(ex); } return(string.Empty); }
public async Task <IActionResult> Profile() { var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new[] { Constants.ScopeUserRead }); var me = await graphApiOperations.GetUserInformation(accessToken); var photo = await graphApiOperations.GetPhotoAsBase64Async(accessToken); ViewData["Me"] = me; ViewData["Photo"] = photo; return(View()); }