private byte[] SendGraphBinaryRequest(string api, string query, GraphApiVersion apiVersion = GraphApiVersion.latest, HttpMethod httpMethod = null) { // First, use ADAL to acquire a token using the app's identity (the credential) // The first parameter is the resource we want an access_token for; in this case, the Graph API. var result = AuthContext.AcquireTokenAsync(msGraphResourceId, Credential).Result; // For B2C user managment, be sure to use the 1.6 Graph API version. using (var http = new HttpClient()) { var url = msGraphEndpoint + (apiVersion == GraphApiVersion.latest ? msGraphVersion : "beta") + api; if (!string.IsNullOrEmpty(query)) { url += "&" + query; } // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme. var request = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = http.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { var error = response.Content.ReadAsStringAsync().Result; var formatted = JsonConvert.DeserializeObject(error); throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); } return(response.Content.ReadAsByteArrayAsync().Result); } }
private async void SingInSilently_Click(object sender, RoutedEventArgs e) { var retryCount = 0; var retry = false; do { retry = false; try { // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired. AdalAuthenticationResult = await AuthContext.AcquireTokenAsync(_webApiResourceId, ClientCredential); TokenInfoText.Text += $"Token Expires: {AdalAuthenticationResult.ExpiresOn.ToLocalTime()}{Environment.NewLine}"; TokenInfoText.Text += $"Access Token: {AdalAuthenticationResult.AccessToken}{Environment.NewLine}"; } catch (AdalException ex) { retry = ex.ErrorCode == "temporarily_unavailable"; TokenInfoText.Text += String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n", DateTime.Now.ToString(), ex.ToString(), retry.ToString()); } } while (retry && (retryCount < 3)); }
private string SendAADGraphRequest(string api, string query = null, string body = null, HttpMethod httpMethod = null) { // First, use ADAL to acquire a token using the app's identity (the credential) // The first parameter is the resource we want an access_token for; in this case, the Graph API. var result = AuthContext.AcquireTokenAsync(aadGraphResourceId, Credential).Result; // For B2C user managment, be sure to use the 1.6 Graph API version. using (var http = new HttpClient()) { var url = aadGraphEndpoint + Tenant + api + (api.Contains("?") ? "&" : "?") + aadGraphVersion; if (!string.IsNullOrEmpty(query)) { url += "&" + query; } // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme. var request = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); if (!string.IsNullOrEmpty(body)) { request.Content = new StringContent(body, Encoding.UTF8, "application/json"); } var response = http.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { var error = response.Content.ReadAsStringAsync().Result; var formatted = JsonConvert.DeserializeObject(error); throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); } return(response.Content.ReadAsStringAsync().Result); } }
/// <summary> /// Attempt interactive authentication through the broker. /// </summary> /// <param name="platformParams"> Additional paramaters for authentication.</param> /// <returns>The AuthenticationResult on succes, null otherwise.</returns> public async Task <AuthenticationResult> SignInWithPrompt(PlatformParameters platformParams) { AuthenticationResult result = null; try { Log.Info(_logTagAuth, "Attempting interactive authentication"); result = await AuthContext.AcquireTokenAsync( _resourceID, _clientID, new Uri(_redirectURI), platformParams); } catch (AdalException e) { string msg = Resource.String.err_auth + e.Message; Log.Error(_logTagAuth, Throwable.FromException(e), msg); Toast.MakeText(platformParams.CallerActivity, msg, ToastLength.Long).Show(); return(null); } isAuthenticated = true; return(result); }
public async Task <string> GetTokenFromClientCredentials(string resource) { if (string.IsNullOrEmpty(resource)) { throw new ArgumentException("A resource is required to retrieve a token from client credentials."); } AuthenticationResult authResult = await AuthContext.AcquireTokenAsync(resource, ClientCredentials); return(authResult.AccessToken); }
private void Authorize() { if (_authResult == null || _authResult.ExpiresOn.AddMinutes(-30) < DateTime.Now) { Task.Run(async() => { _authResult = await AuthContext.AcquireTokenAsync(_resource, _clientId, new Uri(_redirectUrl), new PlatformParameters(PromptBehavior.Always)); }).Wait(); } }
private async void SingInInteractively_Click(object sender, RoutedEventArgs e) { try { //AdalAuthenticationResult = await AuthContext.AcquireTokenAsync(_webApiResourceId, _clientId, new Uri("http://localhost"), new PlatformParameters(PromptBehavior.Always)); AdalAuthenticationResult = await AuthContext.AcquireTokenAsync(_webApiResourceId, _nativeClientId, new Uri(_nativeRedirectUri), new PlatformParameters(PromptBehavior.Always)); TokenInfoText.Text += $"Access Token: {AdalAuthenticationResult.AccessToken}{Environment.NewLine}"; TokenInfoText.Text += $"Token Expires: {AdalAuthenticationResult.ExpiresOn.ToLocalTime()}{Environment.NewLine}"; } catch (Exception ex) { TokenInfoText.Text += String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\n", DateTime.Now.ToString(), ex.ToString()); } }
/// <summary> /// Use client credentials to retrieve auth token /// Typically used to retrieve a token for a different audience /// </summary> /// <param name="userToken">User's token for a given resource</param> /// <param name="resource">Resource the token is for (e.g. https://graph.microsoft.com)</param> /// <returns>Access token for correct audience</returns> public async Task <string> GetTokenOnBehalfOfUserAsync( string userToken, string resource) { if (string.IsNullOrEmpty(userToken)) { throw new ArgumentException("A usertoken is required to retrieve a token for a user."); } if (string.IsNullOrEmpty(resource)) { throw new ArgumentException("A resource is required to retrieve a token for a user."); } UserAssertion userAssertion = new UserAssertion(userToken); AuthenticationResult ar = await AuthContext.AcquireTokenAsync(resource, ClientCredentials, userAssertion); return(ar.AccessToken); }
/// <summary> /// Gets a valid authentication token. Also refreshes the access token if it has expired. /// </summary> /// <remarks> /// Used by the API request generators before making calls to the OneNote APIs. /// </remarks> /// <returns>valid authentication token</returns> internal static async Task <AuthenticationResult> GetAuthenticationResult() { if (String.IsNullOrEmpty(AccessToken)) { try { //look to see if we have an authentication context in cache already //we would have gotten this when we authenticated previously var allCachedItems = AuthContext.TokenCache.ReadItems(); var validCachedItems = allCachedItems .Where(i => i.ExpiresOn > DateTimeOffset.UtcNow.UtcDateTime && IsO365Token(i.IdentityProvider)) .OrderByDescending(e => e.ExpiresOn); var cachedItem = validCachedItems.First(); if (cachedItem != null) { //re-bind AuthenticationContext to the authority source of the cached token. //this is needed for the cache to work when asking for a token from that authority. #if WINDOWS_PHONE_APP AuthContext = AuthenticationContext.CreateAsync(cachedItem.Authority, true).GetResults(); #else AuthContext = new AuthenticationContext(cachedItem.Authority, true); #endif //try to get the AccessToken silently using the resourceId that was passed in //and the client ID of the application. _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId); RefreshAuthTokenIfNeeded().Wait(); } } catch (Exception) { //not in cache; we'll get it with the full oauth flow } } if (string.IsNullOrEmpty(AccessToken)) { try { AuthContext.TokenCache.Clear(); #if WINDOWS_PHONE_APP _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId); if (_authenticationResult == null || string.IsNullOrEmpty(_authenticationResult.AccessToken)) { AuthContext.AcquireTokenAndContinue(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri), null); } #else _authenticationResult = await AuthContext.AcquireTokenAsync(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri)); #endif } catch (Exception) { // Authentication failed if (Debugger.IsAttached) { Debugger.Break(); } } } return(_authenticationResult); }
private async Task <string> GetSupportObserverAccessToken() { var authResult = await AuthContext.AcquireTokenAsync(SupportObserverResourceUri, AADCredentials); return("Bearer " + authResult.AccessToken); }
private async Task <string> GetSupportObserverAccessToken() { var authResult = await AuthContext.AcquireTokenAsync(_configuration[APP_SETTING_OBSERVER_AAD_RESOURCEID], AADCredentials); return("Bearer " + authResult.AccessToken); }
public static async Task <string> FetchTokenAsync() { /*In case of using different profiles (AAD users) from one client * 1. After Authentication during acquiring token, User Id shoud be recorded and saved * 2. UserIdentifier should be created using previously saved UserId, as a hint for context, when acquiring token again * e.g.: UserIdentifier userId = new UserIdentifier(PBIConfig.Profile, UserIdentifierType.UniqueId); * 3. If you want to add new profile (user), than "Prompt Behavior" platform parameter should be set to "Always" * a. in this case, the newly returned client id should be recorded again, and used as context information... */ Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null; // first, try to get a token silently try { switch (PBIConfig.AuthMode) { case "Secret": result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(PBIConfig.ClientId, PBIConfig.ClientSecret)); break; case "ClientId": result = await AuthContext.AcquireTokenSilentAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId); break; case "UserName": result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId, new UserCredential(PBIConfig.UserName)); break; } } catch (AdalException adalException) { // There is no token in the cache; prompt the user to sign-in. if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently || adalException.ErrorCode == AdalError.InteractionRequired) { try { result = await AuthContext.AcquireTokenAsync(PBIConfig.ResourceUrl, PBIConfig.ClientId, new Uri(PBIConfig.RedirectUrl), new PlatformParameters(PromptBehavior.Auto)); } catch (Exception e) { //Log Exception } } else { //Log exception } // An unexpected error occurred. // ShowError(adalException); } catch (Exception e) { //Log Exception } return(result.AccessToken); }
public AuthenticationResult GetAuthenticationResult() { return(AuthContext.AcquireTokenAsync(Audience, ClientCredential).Result); }
protected override async Task <AuthenticationResult> AquireToken(string resourceUri, bool forceLogin) { return(await AuthContext.AcquireTokenAsync(resourceUri, clientId, Credentials)); }