public async void uxLoginButtonClicked(object sender, EventArgs args) { var param = this.PlatformParameters as IPlatformParameters; AuthenticationContext authContext = new AuthenticationContext(Authority); /* * the following line makes the app crash when there is at least one item returned by the call TokenCache.ReadItems()... * Was working before the update to Xamarin4 * * Also tried different PCL profiles with no luck * - portable45-net45+win8 * - portable45-net45+win8+wpa81 */ var token = authContext.TokenCache.ReadItems().FirstOrDefault(); if (token != null) { await authContext.AcquireTokenSilentAsync(ResourceId, ClientId); } else { await authContext.AcquireTokenAsync(ResourceId, ClientId, new Uri(RedirectUrl), param); } token = authContext.TokenCache.ReadItems().FirstOrDefault(); }
public async Task <string> GetTokenForApplication() { string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc) ClientCredential clientcred = new ClientCredential(Startup.clientId, Startup.clientKey); // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database AuthenticationContext authenticationContext = new AuthenticationContext(Startup.aadInstance + tenantID, new ADALTokenCache(signedInUserID)); AuthenticationResult authenticationResult; try { authenticationResult = await authenticationContext.AcquireTokenSilentAsync(Startup.resourceId, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return(authenticationResult.AccessToken); }catch (AdalException e) { if (e.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authenticationContext.TokenCache.Clear(); throw e; } } return(null); }
public async Task <AuthResult> GetAccessToken(AuthenticationOptions authOptions, IDialogContext context) { AuthResult authResult; if (context.UserData.TryGetValue($"{this.Name}{ContextConstants.AuthResultKey}", out authResult)) { try { InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache); AuthenticationContext authContext = new AuthenticationContext(authOptions.Authority, tokenCache); var result = await authContext.AcquireTokenSilentAsync(authOptions.ResourceId, new ClientCredential(authOptions.ClientId, authOptions.ClientSecret), new UserIdentifier(authResult.UserUniqueId, UserIdentifierType.UniqueId)); authResult = result.FromADALAuthenticationResult(tokenCache); context.StoreAuthResult(authResult, this); } catch (Exception ex) { Trace.TraceError("Failed to renew token: " + ex.Message); await context.PostAsync("Your credentials expired and could not be renewed automatically!"); await Logout(authOptions, context); return(null); } return(authResult); } return(null); }
//public IActionResult TimeConsuming() //{ // var uniqueName = HttpContext.User.Claims.First(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Value; // UsageTelemetry.Track(uniqueName, ArdaUsage.Report_Show); // return View(); //} public async Task <IActionResult> TimeConsuming() { string userObjectID = HttpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var tokenCache = new NaiveSessionCache(userObjectID, NaiveSessionCacheResource.PowerBi, _cache); //ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret); AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, tokenCache); var authenticationResult = await authContext.AcquireTokenSilentAsync(Startup.PowerBIResourceId, Startup.ClientId); var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); using (var client = new PowerBIClient(new Uri(Startup.PowerBIApiUrl), tokenCredentials)) { // You will need to provide the GroupID where the dashboard resides. ODataResponseListReport reports = await client.Reports.GetReportsInGroupAsync(Startup.PowerBIGroupId); // Get the first report in the group. Report report = reports.Value.FirstOrDefault(); // Generate Embed Token. var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(Startup.PowerBIGroupId, report.Id, generateTokenRequestParameters); // Generate Embed Configuration. var embedConfig = new EmbedConfig() { EmbedToken = tokenResponse, EmbedUrl = report.EmbedUrl, Id = report.Id }; return(View("PowerBI", embedConfig)); } }
// Get an access token. First tries to get the token from the token cache. public async Task <string> GetUserAccessTokenAsync() { string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; HttpContextBase httpContextBase = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase; SessionTokenCache tokenCache = new SessionTokenCache(signedInUserID, httpContextBase); //var cachedItems = tokenCache.ReadItems(); // see what's in the cache AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, tokenCache); ClientCredential clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret); string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; UserIdentifier userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); try { AuthenticationResult result = await authContext.AcquireTokenSilentAsync(SettingsHelper.GraphResourceId, clientCredential, userId); return(result.AccessToken); } // Unable to retrieve the access token silently. catch (AdalException ex) { HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( new AuthenticationProperties() { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); throw new Exception($" {ex.Message}"); } }
private static async Task <string> GetAccessTokenAsync() { // determine authorization URL for current tenant string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string tenantAuthority = aadInstance + tenantID; // create ADAL cache object ApplicationDbContext db = new ApplicationDbContext(); string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID); // create authentication context AuthenticationContext authenticationContext = new AuthenticationContext(tenantAuthority, userTokenCache); // create client credential object using client ID and client Secret"]; ClientCredential clientCredential = new ClientCredential(clientId, clientSecret); // create user identifier object for logged on user string objectIdentifierId = "http://schemas.microsoft.com/identity/claims/objectidentifier"; string userObjectID = ClaimsPrincipal.Current.FindFirst(objectIdentifierId).Value; UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId); // get access token for Power BI Service API from AAD AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( resourceUrlPowerBi, clientCredential, userIdentifier); // return access token back to user return(authenticationResult.AccessToken); }
private async void acquireTokenSilentButton_Click(object sender, EventArgs e) { this.accessTokenTextView.Text = string.Empty; EditText email = FindViewById <EditText>(Resource.Id.email); string value = null; try { AuthenticationContext ctx = new AuthenticationContext("https://login.microsoftonline.com/common"); AuthenticationResult result = await ctx .AcquireTokenSilentAsync("https://graph.windows.net", "<CLIENT_ID>", UserIdentifier.AnyUser, new PlatformParameters(this, false)).ConfigureAwait(false); value = result.AccessToken; } catch (Java.Lang.Exception ex) { throw new Exception(ex.Message + "\n" + ex.StackTrace); } catch (Exception exc) { value = exc.Message; } this.accessTokenTextView.Text = value; }
//292916 Ensure AcquireTokenSilent tests exist in ADAL.NET for public clients public async Task ExpiredATValidRTInCache_GetNewATRTFromServiceAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(), PostData = new Dictionary <string, string>() { { "client_id", TestConstants.DefaultClientId }, { "grant_type", "refresh_token" }, { "refresh_token", "some_rt" } } }); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some_rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow) }; AuthenticationResult result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier(TestConstants.DefaultDisplayableId, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false); Assert.IsNotNull(result); }
public void AcquireTokenSilentServiceErrorTest() { TokenCache cache = new TokenCache(); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityCommonTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, "unique_id", "*****@*****.**"); cache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "something-invalid", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow) }; AuthenticationContext context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, cache); var ex = AssertException.TaskThrows <AdalSilentTokenAcquisitionException>(async() => { HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler(TestConstants.GetTokenEndpoint(TestConstants.DefaultAuthorityCommonTenant)) { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage() }); await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)).ConfigureAwait(false); }); Assert.AreEqual(AdalError.FailedToAcquireTokenSilently, ex.ErrorCode); Assert.AreEqual(AdalErrorMessage.FailedToAcquireTokenSilently, ex.Message); Assert.IsNotNull(ex.InnerException); Assert.IsTrue(ex.InnerException is AdalException); Assert.AreEqual(((AdalException)ex.InnerException).ErrorCode, "invalid_grant"); // There should be one cached entry. Assert.AreEqual(1, context.TokenCache.Count); }
public async Task AcquireTokenWithInvalidResourceTestAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache()); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "some-access-token", DateTimeOffset.UtcNow) }; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateInvalidRequestTokenResponseMessage() }); try { await context.AcquireTokenSilentAsync("random-resource", TestConstants.DefaultClientId); } catch (AdalServiceException exc) { Assert.AreEqual(AdalError.FailedToRefreshToken, exc.ErrorCode); } }
public async Task <ActionResult> Contact() { ViewBag.Message = "Your contact page."; var userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; var userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var ctx = new AuthenticationContext( Startup.aadInstance + tenantId, new RedisTokenCache(userId)); var authn = await ctx.AcquireTokenSilentAsync( Startup.GraphResourceId, Startup.Credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authn.AccessToken); var req = Startup.GraphResourceId + "/me?api-version=1.6"; var meJson = await client.GetStringAsync(req); var me = new { mobile = "" }; me = JsonConvert.DeserializeAnonymousType(meJson, me); ViewBag.Mobile = me.mobile; return(View()); }
private string GetGraphAccessToken() { string accessToken = string.Empty; string authority = _configuration.GetValue <string>("OpenIdConnect:Authority"); TokenCache cache = _tokenCacheFactory.CreateForUser(User); AuthenticationContext authContext = new AuthenticationContext(authority, cache); // App's credentials may be needed if access tokens need to be refreshed with a refresh token string clientId = _configuration.GetValue <string>("OpenIdConnect:ClientId"); string clientSecret = _configuration.GetValue <string>("OpenIdConnect:ClientSecret"); ClientCredential credential = new ClientCredential(clientId, clientSecret); string userId = User.GetObjectId(); AuthenticationResult result = null; try { result = authContext.AcquireTokenSilentAsync( _configuration.GetValue <string>("OpenIdConnect:Resource"), credential, new UserIdentifier(userId, UserIdentifierType.UniqueId)).Result; accessToken = result.AccessToken; } catch (Exception ex) { HttpContext.SignOutAsync().Wait(); } return(accessToken); }
public async Task <String> GetAccessTokenAsync(IReadOnlyList <string> scopes) { if (Type == ConnectedDevicesAccountType.MSA) { return(await MSAOAuthHelpers.GetAccessTokenUsingRefreshTokenAsync(Token, scopes)); } else if (Type == ConnectedDevicesAccountType.AAD) { var authContext = new AuthenticationContext("https://login.microsoftonline.com/common"); UserIdentifier aadUserId = new UserIdentifier(Id, UserIdentifierType.UniqueId); AuthenticationResult result; try { result = await authContext.AcquireTokenSilentAsync(scopes[0], Secrets.AAD_CLIENT_ID); } catch (Exception ex) { Logger.Instance.LogMessage($"Token request failed: {ex.Message}"); // Token may have expired, try again non-silently result = await authContext.AcquireTokenAsync(scopes[0], Secrets.AAD_CLIENT_ID, new Uri(Secrets.AAD_REDIRECT_URI), new PlatformParameters(PromptBehavior.Auto, true)); } return(result.AccessToken); } else { throw new Exception("Invalid Account Type"); } }
/// <inheritdoc /> protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options) { var app = PreRegisteredApps.CommonCacheTestV1; string resource = PreRegisteredApps.MsGraph; CommonCacheTestUtils.EnsureCacheFileDirectoryExists(); var tokenCache = new FileBasedTokenCache( CommonCacheTestUtils.AdalV3CacheFilePath, CommonCacheTestUtils.MsalV2CacheFilePath); var authenticationContext = new AuthenticationContext(app.Authority, tokenCache); try { var result = await authenticationContext.AcquireTokenSilentAsync( resource, app.ClientId, new UserIdentifier(options.Username, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false); Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' from the cache"); return(new CacheExecutorResults(result.UserInfo.DisplayableId, true)); } catch (AdalSilentTokenAcquisitionException) { var result = await authenticationContext.AcquireTokenAsync( resource, app.ClientId, new UserPasswordCredential(options.Username, options.UserPassword)).ConfigureAwait(false); Console.WriteLine($"got token for '{result.UserInfo.DisplayableId}' without the cache"); return(new CacheExecutorResults(result.UserInfo.DisplayableId, false)); } }
private static async Task <string> AcquireTokenNoContextAsync(string resource, string errorTrace, string tenantId, string userObjectId, bool allowFallbackToApp1) { string authority = string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId); AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCache(userObjectId)); try { var result = await authContext.AcquireTokenSilentAsync(resource, SettingsHelper.GetApp2Credentials(), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); return(result.AccessToken); } catch (AdalException exception) { Trace.TraceError(errorTrace); Trace.TraceError("Cannot acquire token on app2"); Trace.TraceError("...do not fall back on app1"); if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently) { authContext.TokenCache.Clear(); } throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } }
//292916 Ensure AcquireTokenSilent tests exist in ADAL.NET for public clients public async Task AcquireTokenSilentTestWithValidTokenInCacheAsync() { var context = new AuthenticationContext(TestConstants.DefaultAuthorityHomeTenant, true, new TokenCache()); TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant, TestConstants.DefaultResource, TestConstants.DefaultClientId, TokenSubjectType.User, TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId); context.TokenCache.tokenCacheDictionary[key] = new AuthenticationResultEx { RefreshToken = "some-rt", ResourceInResponse = TestConstants.DefaultResource, Result = new AuthenticationResult("Bearer", "existing-access-token", DateTimeOffset.UtcNow + TimeSpan.FromMinutes(100)) }; AuthenticationResult result = await context.AcquireTokenSilentAsync(TestConstants.DefaultResource, TestConstants.DefaultClientId, new UserIdentifier("unique_id", UserIdentifierType.UniqueId)).ConfigureAwait(false); Assert.IsNotNull(result); Assert.AreEqual("existing-access-token", result.AccessToken); // There should be one cached entry. Assert.AreEqual(1, context.TokenCache.Count); }
/// <summary> /// Used to get authentication result for Integrated Windows Authentication scenario, where the token may already be in ADAL cache. /// </summary> /// <param name="authority"></param> /// <param name="resource"></param> /// <param name="clientId"></param> /// <returns></returns> public async Task <AppAuthenticationResult> AcquireTokenSilentAsync(string authority, string resource, string clientId) { AuthenticationContext authenticationContext = new AuthenticationContext(authority); var authResult = await authenticationContext.AcquireTokenSilentAsync(resource, clientId).ConfigureAwait(false); return(AppAuthenticationResult.Create(authResult)); }
public async Task GrantRoleToServicePrincipalOnSubscription(string objectId, string subscriptionId, string directoryId) { string signedInUserUniqueName = signedInUserService.GetSignedInUserName(); // Aquire Access Token to call Azure Resource Manager ClientCredential credential = new ClientCredential(azureADSettings.ClientId, azureADSettings.ClientSecret); // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB AuthenticationContext authContext = new AuthenticationContext( string.Format(azureADSettings.Authority, directoryId), new TableTokenCache(signedInUserUniqueName, azureADSettings.TokenStorageConnectionString)); AuthenticationResult result = await authContext.AcquireTokenSilentAsync(azureADSettings.ResourceManagerIdentifier, credential, new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId)); // Create role assignment for application on the subscription string roleAssignmentId = Guid.NewGuid().ToString(); string roleDefinitionId = await GetRoleId(azureADSettings.RequiredARMRoleOnSubscription, subscriptionId, directoryId); string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/roleassignments/{2}?api-version={3}", azureADSettings.ResourceManagerUrl, subscriptionId, roleAssignmentId, azureADSettings.ARMAuthorizationRoleAssignmentsAPIVersion); HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); StringContent content = new StringContent("{\"properties\": {\"roleDefinitionId\":\"" + roleDefinitionId + "\",\"principalId\":\"" + objectId + "\"}}"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); }
private async Task <AuthenticationResult> TryFetchTokenSilently() { AuthenticationResult result = null; // first, try to get a token silently try { return(result = await _authenticationContext.AcquireTokenSilentAsync(aadResourceAppId, _authConfig.ClientId)); } 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) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("No token in the cache"); return(result); } Log("An unexpected error occurred.\r\n" + adalException); } return(result); }
/// <summary> /// Authenticate. /// </summary> void Authenticate() { #if !PCL if (RootConfiguration == null) { RootConfiguration = (PowerBIConfiguration)ConfigurationManager.GetSection(typeof(PowerBIConfiguration).Name); } #endif if (AuthenticationContext == null) { var tokenCache = new TokenCache(); AuthenticationContext = new AuthenticationContext(Configuration.Authority, tokenCache); } //For PCL we need to use the ADAL 3.O alpha. Because this version isn't a release we use compilation //condition to not use it in the classic version (PCL version of the PowerBI.Api.Client is also a Pre-Release) //We use synchronous call (We be change in the next version of the library) #if !PCL var authResult = string.IsNullOrEmpty(AccessToken) ? AuthenticationContext.AcquireToken(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password)) : AuthenticationContext.AcquireTokenSilent(Configuration.Resource, Configuration.Client); AccessToken = authResult.AccessToken; #else var task = string.IsNullOrEmpty(AccessToken) ? AuthenticationContext.AcquireTokenAsync(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password)) : AuthenticationContext.AcquireTokenSilentAsync(Configuration.Resource, Configuration.Client); Task.WaitAll(task); AccessToken = task.Result.AccessToken; #endif }
// Get an access token for the given context and resource ID silently. We run this only after the user has already been authenticated. private static async Task <string> GetTokenHelperAsync(AuthenticationContext context, string resourceId) { string accessToken = null; AuthenticationResult result = null; result = await context.AcquireTokenSilentAsync(resourceId, ClientID); if (result.Status == AuthenticationStatus.Success) { accessToken = result.AccessToken; // Store values for logged-in user, tenant ID, and authority, so that // they can be re-used if the user re-opens the app without disconnecting. App._settings.LoggedInUser = result.UserInfo.UniqueId; App._settings.UserEmail = result.UserInfo.DisplayableId; App._settings.TenantId = result.TenantId; App._settings.LastAuthority = context.Authority; return(accessToken); } else { return(null); } }
//Vittorio Approved! private async static Task <AuthenticationResult> GetAccessToken(string resourceId) { var authContext = new AuthenticationContext(Authority); AuthenticationResult authResult = null; if (Settings.TenantId == "common") { authResult = await authContext.AcquireTokenAsync(resourceId, clientId, returnUri, PlatformParameters); } else { try { authResult = await authContext.AcquireTokenSilentAsync(resourceId, clientId); } catch (AdalSilentTokenAcquisitionException ex) { //failed } if (authResult == null) { authResult = await authContext.AcquireTokenAsync(resourceId, clientId, returnUri, PlatformParameters); } } Settings.TenantId = authResult.TenantId; return(authResult); }
public async Task OnGet() { // Because we signed-in already in the WebApp, the userObjectId is know string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; // Using ADAL.Net, get a bearer token to access the TodoListService AuthenticationContext authContext = new AuthenticationContext( authority: _azureAdOptions.Authority, tokenCache: new NaiveSessionCache( userId: userObjectID, cache: _memoryCache)); ClientCredential credential = new ClientCredential( clientId: _azureAdOptions.ClientId, clientSecret: _azureAdOptions.ClientSecret); AuthenticationResult result = await authContext.AcquireTokenSilentAsync( resource : _azureAdOptions.ApiResourceId, clientCredential : credential, userId : new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var content = await client.GetStringAsync("https://localhost:5001/api/values"); Json = JArray.Parse(content).ToString(); }
public async Task <string> AcquireTokenAsync(string resource) { if (!await authorizationService.AuthorizeAsync(httpContextAccessor.HttpContext?.User, "FacilityProviderOnly")) { return(null); } var userId = GetUserId(); var clientCredential = new ClientCredential(authOptions.ClientId, authOptions.ClientSecret); var authenticationContext = new AuthenticationContext(authOptions.Authority, new DistributedTokenCache(distributedCache, userId)); try { var user = !string.IsNullOrEmpty(userId) ? new UserIdentifier(userId, UserIdentifierType.UniqueId) : UserIdentifier.AnyUser; var authenticationResult = await authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, user); return(authenticationResult.AccessToken); } catch (AdalSilentTokenAcquisitionException) { throw new ReauthenticationRequiredException(); } }
/// <summary> /// Method that will get the Microsoft Graph token. /// </summary> /// <param name="graphConfigurationDetails">The graph configuration details.</param> /// <returns>The string that represents the Microsoft Graph token.</returns> private async Task <string> GetAccessTokenAsync(GraphConfigurationDetails graphConfigurationDetails) { string authority = $"{graphConfigurationDetails.Instance}{graphConfigurationDetails.TenantId}"; var cache = new RedisTokenCache(this.cache, graphConfigurationDetails.ClientId); var authContext = new AuthenticationContext(authority, cache); var userIdentity = new UserIdentifier(graphConfigurationDetails.ShiftsAdminAadObjectId, UserIdentifierType.UniqueId); try { var result = await authContext.AcquireTokenSilentAsync( "https://graph.microsoft.com", new ClientCredential( graphConfigurationDetails.ClientId, graphConfigurationDetails.ClientSecret), userIdentity).ConfigureAwait(false); return(result.AccessToken); } catch (AdalException adalEx) { this.telemetryClient.TrackException(adalEx); var retryResult = await authContext.AcquireTokenAsync( "https://graph.microsoft.com", new ClientCredential( graphConfigurationDetails.ClientId, graphConfigurationDetails.ClientSecret)).ConfigureAwait(false); return(retryResult.AccessToken); } }
private AuthenticationResult RefreshAccessToken(UserInfo userInfo, AuthenticationAccessToken type) { AuthenticationResult result = null; UserIdentifier userId = ConvertToUniqueIdentifier(userInfo); try { var authority = $"{AadInstance}{Tenant}"; var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared); //var authparams = new PlatformParameters(PromptBehavior.Auto); string resource = type == AuthenticationAccessToken.IntegrationAccount ? Resource : KeyvaultResource; result = authContext.AcquireTokenSilentAsync(resource, ClientId, userId).Result; if (result != null && !string.IsNullOrEmpty(result.AccessToken)) { return(result); } else { throw new Exception("Failed to retrieve the access token"); } } catch (Exception x) { throw x; } }
public async Task <string> GetUserAccessToken(string redirectUri) { AuthenticationContext authContext = new AuthenticationContext(Authority, false, TokenCache); ClientCredential credential = new ClientCredential(AppId, AppSecret); try { AuthenticationResult authResult = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(TokenCache.UserObjectId, UserIdentifierType.UniqueId)); return(authResult.AccessToken); } catch (AdalSilentTokenAcquisitionException) { HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( new AuthenticationProperties() { RedirectUri = redirectUri }, OpenIdConnectAuthenticationDefaults.AuthenticationType); return(null); } }
public SecurityToken RequestToken(string issuer, string appliesTo, RecordsManagerCredentials credentials) { var authContext = new AuthenticationContext(Constants.WAAD_AUTHORITY); AuthenticationResult result = null; // first, try to get a token silently try { result = authContext.AcquireTokenSilentAsync(appId, Constants.WAAD_CLIENTID).Result; } catch (AggregateException exc) { AdalException ex = exc.InnerException as AdalException; // There is no token in the cache; prompt the user to sign-in. if (ex != null && ex.ErrorCode != "failed_to_acquire_token_silently") { throw; } } if (result == null) { result = this.RunSync(async() => { return(await authContext.AcquireTokenAsync(appId, Constants.WAAD_CLIENTID, new UserPasswordCredential(credentials.Username, credentials.Password))); }); } return(new SecurityToken(result.AccessToken, result.AccessTokenType, result.ExpiresOn.DateTime)); }
public async Task <IActionResult> Index() { string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; string authority = $"{_configuration["AzureAd:Instance"]}{_configuration["AzureAd:TenantId"]}"; string client_id = _configuration["AzureAd:ClientId"]; string client_secret = _configuration["AzureAd:ClientSecret"]; try { AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectID, HttpContext.Session)); ClientCredential credential = new ClientCredential(client_id, client_secret); AuthenticationResult result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = await client.GetAsync("https://graph.microsoft.com/v1.0/me"); var cont = await response.Content.ReadAsStringAsync(); ViewData["me"] = cont; } catch { ViewData["me"] = "Failed to access MS Graph"; } return(View()); }
private async Task InitializeLogin() { // // As the application starts, try to get an access token without prompting the user. If one exists, populate the To Do list. If not, continue. // authContext = new AuthenticationContext(authority, new FileCache()); AuthenticationResult result = null; try { result = await authContext.AcquireTokenSilentAsync(todoListResourceId, clientId); // A valid token is in the cache - get the To Do list. SignInButton.Content = "Clear Cache"; GetTodoList(); } catch (AdalException ex) { if (ex.ErrorCode == FAILED_SILENT) { // There are no tokens in the cache. Proceed without calling the To Do list service. } else { // An unexpected error occurred. string message = ex.Message; if (ex.InnerException != null) { message += "Inner Exception : " + ex.InnerException.Message; } MessageBox.Show(message); } return; } }
public async Task<ActionResult> Index() { // By using this version of the AuthenticationContext constructor, // we are using the default in-memory token cache. In a real app, you would // want to provide an implementation of TokenCache that saves the data somewhere // so that you could persist it if restarting the app, etc. AuthenticationContext authContext = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(appId, appSecret); AuthenticationResult authResult = null; ViewBag.Message = TempData["message"]; try { authResult = await authContext.AcquireTokenSilentAsync(scopes, credential, UserIdentifier.AnyUser); ViewBag.UserName = GetUserEmail(authContext, appId); } catch (AdalException ex) { if (ex.ErrorCode == "failed_to_acquire_token_silently") { // We don't have a token in the cache OR the token couldn't be refreshed // We need to have the user sign in Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme)); ViewBag.LoginUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, appId, redirectUri, UserIdentifier.AnyUser, null); } else { TempData["error_message"] = ex.Message; RedirectToAction("Error"); } } return View(); }
public async Task<ActionResult> Calendar() { AuthenticationContext authContext = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(appId, appSecret); AuthenticationResult authResult = null; try { authResult = await authContext.AcquireTokenSilentAsync(scopes, credential, UserIdentifier.AnyUser); } catch (AdalException ex) { TempData["message"] = "Please sign in to continue"; return Redirect("/"); } var client = new Outlook(); client.anchorMailbox = GetUserEmail(authContext, appId); ViewBag.UserName = client.anchorMailbox; DateTime viewStart = DateTime.Now.ToUniversalTime(); DateTime viewEnd = viewStart.AddHours(3); var result = await client.GetCalendarView(authResult.Token, client.anchorMailbox, viewStart, viewEnd); return View(result); }