/// <summary> /// Authentication is done using the preview version of the Microsoft Identity Client (Microsoft Authentication Library or MSAL). /// See https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview and https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-libraries /// </summary> /// <returns>Object holding information about the authentication flow</returns> private AuthenticationResult Authenticate() { var appCredentials = new ClientCredential(this.appPassword); var authority = new Uri(this.AADLogin, this.aadDomain).AbsoluteUri; var clientApplication = new ConfidentialClientApplication(this.appId, authority, this.RedirectUri, appCredentials, new TokenCache(), new TokenCache()); AuthenticationResult authenticationResult = clientApplication.AcquireTokenForClientAsync(DefaultScope).GetAwaiter().GetResult(); return(authenticationResult); }
/// <summary> /// Get Token for App. /// </summary> /// <returns>Token for app.</returns> public static async Task <string> GetTokenForAppAsync() { AuthenticationResult authResult; authResult = await IdentityAppOnlyApp.AcquireTokenForClientAsync(new string[] { "https://graph.microsoft.com/.default" }); TokenForApp = authResult.AccessToken; return(TokenForApp); }
public async Task ForceRefreshParameterTrueTestAsync() { await RunWithMockHttpAsync( async (httpManager, serviceBundle, receiver) => { httpManager.AddInstanceDiscoveryMockHandler(); var cache = new TokenCache(); _tokenCacheHelper.PopulateCache(cache.TokenCacheAccessor); string authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityTestTenant, false) .CanonicalAuthority; var app = new ConfidentialClientApplication( serviceBundle, MsalTestConstants.ClientId, authority, MsalTestConstants.RedirectUri, new ClientCredential(MsalTestConstants.ClientSecret), null, cache) { ValidateAuthority = false }; httpManager.AddMockHandlerForTenantEndpointDiscovery(app.Authority); //add mock response for successful token retrival const string TokenRetrievedFromNetCall = "token retrieved from network call"; httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessfulClientCredentialTokenResponseMessage(TokenRetrievedFromNetCall) }); var result = await app.AcquireTokenForClientAsync(MsalTestConstants.Scope, true).ConfigureAwait(false); Assert.AreEqual(TokenRetrievedFromNetCall, result.AccessToken); // make sure token in Cache was updated ICollection <MsalAccessTokenCacheItem> accessTokens = cache.GetAllAccessTokensForClient(new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))); var accessTokenInCache = accessTokens .Where(item => ScopeHelper.ScopeContains(item.ScopeSet, MsalTestConstants.Scope)) .ToList().FirstOrDefault(); Assert.AreEqual(TokenRetrievedFromNetCall, accessTokenInCache.Secret); Assert.IsNotNull( receiver.EventsReceived.Find( anEvent => // Expect finding such an event anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.WasSuccessfulKey] == "true" && anEvent[ApiEvent.ApiIdKey] == "727")); }).ConfigureAwait(false); }
public static void Run([TimerTrigger("*/30 * * * * *")] TimerInfo myTimer, TraceWriter log) { log.Info($"C# Timer trigger function executed at: {DateTime.Now}"); try { ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(ConfigurationManager.AppSettings["clientId"], String.Format(authorityFormat, tenantId), ConfigurationManager.AppSettings["replyUri"], new ClientCredential(ConfigurationManager.AppSettings["clientSecret"]), null, new TokenCache()); AuthenticationResult authResult = daemonClient.AcquireTokenForClientAsync(new string[] { msGraphScope }).GetAwaiter().GetResult(); // Query for list of users in the tenant HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, msGraphQuery); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult(); // If the token we used was insufficient to make the query, drop the token from the cache. // The Users page of the website will show a message to the user instructing them to grant // permissions to the app (see User/Index.cshtml). if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) { // BUG: Here, we should clear MSAL's app token cache to ensure that on a subsequent call // to SyncController, MSAL does not return the same access token that resulted in this 403. // By clearing the cache, MSAL will be forced to retrieve a new access token from AAD, // which will contain the most up-to-date set of permissions granted to the app. Since MSAL // currently does not provide a way to clear the app token cache, we have commented this line // out. Thankfully, since this app uses the default in-memory app token cache, the app still // works correctly, since the in-memory cache is not persistent across calls to SyncController // anyway. If you build a persistent app token cache for MSAL, you should make sure to clear // it at this point in the code. // //daemonClient.AppTokenCache.Clear(Startup.clientId); log.Error("Unable to issue query: Received " + response.StatusCode + " in Run method"); } if (!response.IsSuccessStatusCode) { log.Error("Unable to issue query: Received " + response.StatusCode + " in Run method"); } // Record users in the data store (note that this only records the first page of users) string json = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json); usersByTenant[tenantId] = users.value; log.Info("Successfully synchronized " + users.value.Count + " users!"); } catch (Exception oops) { log.Error(oops.Message, oops, "AzureSyncFunction.UserSync.Run"); } }
public async Task Get(string tenantId) { // Get a token for the Microsoft Graph. If this line throws an exception for // any reason, we'll just let the exception be returned as a 500 response // to the caller, and show a generic error message to the user. ConfidentialClientApplication daemonClient = new ConfidentialClientApplication( Startup.clientId, String.Format(authorityFormat, tenantId), Startup.redirectUri, new ClientCredential(Startup.clientSecret), null, new TokenCache()); AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync( new string[] { msGraphScope }); // Query for list of users in the tenant HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, msGraphQuery); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // If the token we used was insufficient to make the query, drop the token from the cache. // The Users page of the website will show a message to the user instructing them to grant // permissions to the app (see User/Index.cshtml). if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) { // BUG: Here, we should clear MSAL's app token cache to ensure that on a subsequent call // to SyncController, MSAL does not return the same access token that resulted in this 403. // By clearing the cache, MSAL will be forced to retrieve a new access token from AAD, // which will contain the most up-to-date set of permissions granted to the app. Since MSAL // currently does not provide a way to clear the app token cache, we have commented this line // out. Thankfully, since this app uses the default in-memory app token cache, the app still // works correctly, since the in-memory cache is not persistent across calls to SyncController // anyway. If you build a persistent app token cache for MSAL, you should make sure to clear // it at this point in the code. // //daemonClient.AppTokenCache.Clear(Startup.clientId); } if (!response.IsSuccessStatusCode) { throw new HttpResponseException(response.StatusCode); } // Record users in the data store (note that this only records the first page of users) string json = await response.Content.ReadAsStringAsync(); MsGraphUserListResponse users = JsonConvert.DeserializeObject <MsGraphUserListResponse>(json); usersByTenant[tenantId] = users.value; return; }
private async Task RefreshTokenIfNecessaryAsync() { if (expirationMoment <= DateTimeOffset.UtcNow.AddSeconds(-5)) { var authority = $"{azureAdConfiguration.Instance}{azureAdConfiguration.TenantId}"; var redirectUri = "http://localhost"; //mock var daemonClient = new ConfidentialClientApplication(azureAdConfiguration.ClientId, authority, redirectUri, new ClientCredential(azureAdConfiguration.ClientSecret), null, new TokenCache()); var authResult = await daemonClient.AcquireTokenForClientAsync(new string[] { $"{dynamicsConfiguration.OrganizationUri}.default" }); token = authResult.AccessToken; expirationMoment = authResult.ExpiresOn; } }
private static async Task <string> AcquireAccessTokenAsync() { var app = new ConfidentialClientApplication( _settings.ClientId, _settings.Authority, "https://localhost", new ClientCredential(_settings.ClientSecret), userTokenCache: null, appTokenCache: new TokenCache()); var result = await app.AcquireTokenForClientAsync(new[] { $"{_settings.EmployeeApiAppIdUri}/.default" }); return(result.AccessToken); }
private static async Task <string> getAdTokenAsync(IConfiguration configuration, string azureAdSectionName = null) { azureAdSectionName = azureAdSectionName ?? AzureADDefaults.AuthenticationScheme; var adSection = configuration.GetSection(azureAdSectionName) ?? configuration.GetSection("AzureAD") ?? configuration.GetSection("AzureAd"); var adOptions = new AzureADOptions(); adSection.Bind(adOptions); var clientId = adSection["ClientId"]; if (string.IsNullOrWhiteSpace(clientId)) { throw new Exception($"require configuration for AzureAD.ClientId"); } var clientSecret = adSection["ClientSecret"]; if (string.IsNullOrWhiteSpace(clientSecret)) { throw new Exception($"require configuration for AzureAD.ClientSecret"); } //var instance = adSection["Instance"]; //if (string.IsNullOrWhiteSpace(instance)) { throw new Exception($"require configuration for AzureAD.Instance"); } string[] scopes = new string[] { "https://graph.microsoft.com/.default" }; var credential = new ClientCredential(secret: clientSecret); var authority = adSection["Instance"] ?? "https://graph.windows.net/"; var authContext = new ConfidentialClientApplication( clientId: clientId, authority: authority, redirectUri: "http://daemon", clientCredential: credential, userTokenCache: null, appTokenCache: new TokenCache() ); try { var authResult = await authContext.AcquireTokenForClientAsync(scopes); return(authResult.AccessToken); } catch (MsalServiceException ex) { // Case when ex.Message contains: // AADSTS70011 Invalid scope. The scope has to be of the form "https://resourceUrl/.default" // Mitigation: change the scope to be as expected //logger.LogError($"getAdTokenAsync: {ex.Message}"); throw; } }
public static async Task <AuthenticationResult> GetAuthenticationResult() { var appConfig = new ApplicationConfiguration(); var clientCred = new ClientCredential(appConfig.GraphClientSecret); var clientApp = new ConfidentialClientApplication( appConfig.GraphClientId, $"{appConfig.GraphAuthority}/{appConfig.GraphTenantId}", appConfig.GraphRedirectUrl, clientCred, null, null); return(await clientApp.AcquireTokenForClientAsync(appConfig.GraphScope.Split(","))); }
public string GetAuthToken() { if (_authenticationResult == null) { var clientCredential = new ClientCredential(appKey); //am not bothering with inbuilt caching mech, as tests won't take that that long to run ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(clientId, authority, redirectUri, clientCredential, null, new TokenCache()); _authenticationResult = daemonClient .AcquireTokenForClientAsync(new string[] { todoListResourceId + "/.default" }).Result; } return(_authenticationResult.AccessToken); }
/// <summary> /// Retrieves a token for the Microsoft Graph using the client secret and scope /// </summary> /// <returns></returns> private async Task <string> AuthenticateToGraphAsync() { MSALCache appTokenCache = new MSALCache(_clientId); ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(_clientId, string.Format(_authorityFormat, _tenantId), _redirectUri, new ClientCredential(_clientSecret), null, appTokenCache.GetMsalCacheInstance()); AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(new[] { _graphScope }); if (string.IsNullOrEmpty(authResult?.AccessToken)) { throw new Exception("A token could not be retrieve from Microsft Graph"); } return(authResult?.AccessToken); }
private static void RunClientCredentialWithCertificate() { ClientCredential cc = new ClientCredential(new ClientAssertionCertificate(GetCertificateByThumbprint("<THUMBPRINT>"))); ConfidentialClientApplication app = new ConfidentialClientApplication(ClientIdForConfidentialApp, "http://localhost", cc, new TokenCache(), new TokenCache()); try { AuthenticationResult result = app.AcquireTokenForClientAsync(new string[] { "User.Read.All" }, true).Result; } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { Console.ReadKey(); } }
static void Main(string[] args) { ClientCredential cc = new ClientCredential(new ClientAssertionCertificate(new System.Security.Cryptography.X509Certificates.X509Certificate2("cert.pfx"))); ConfidentialClientApplication app = new ConfidentialClientApplication("<client-id>", "http://localhost", cc, new TokenCache(), new TokenCache()); try { AuthenticationResult result = app.AcquireTokenForClientAsync(new string[] { "User.Read.All" }).Result; } catch (Exception exc) { Console.WriteLine(exc.Message); } finally { Console.ReadKey(); } }
public async Task ForceRefreshParameterTrueTestAsync() { var cache = new TokenCache(); TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor); var authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false).CanonicalAuthority; var app = new ConfidentialClientApplication(TestConstants.ClientId, authority, TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret), null, cache) { ValidateAuthority = false }; //add mock response for tenant endpoint discovery HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(app.Authority) }); //add mock response for successful token retrival const string tokenRetrievedFromNetCall = "token retrieved from network call"; HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessfulClientCredentialTokenResponseMessage(tokenRetrievedFromNetCall) }); var result = await app.AcquireTokenForClientAsync(TestConstants.Scope, true); Assert.AreEqual(tokenRetrievedFromNetCall, result.AccessToken); // make sure token in Cache was updated var accessTokens = cache.GetAllAccessTokensForClient(new RequestContext(Guid.NewGuid(), null)); var accessTokenInCache = accessTokens.Where( item => item.ScopeSet.ScopeContains(TestConstants.Scope)) .ToList() .FirstOrDefault(); Assert.AreEqual(tokenRetrievedFromNetCall, accessTokenInCache?.AccessToken); Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent => // Expect finding such an event anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.WasSuccessfulKey] == "true" && anEvent[ApiEvent.ApiIdKey] == "727")); }
public void GetTokenFromAzure() { AuthenticationResult token = null; "When I request a Token" .x(async() => { var clientCredential = new ClientCredential(appKey); ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(clientId, authority, redirectUri, clientCredential, null, new TokenCache()); token = await daemonClient.AcquireTokenForClientAsync(new string[] { "https://graph.microsoft.com/.default" }); }); "Then the token should not not be null" .x(() => { token.Should().NotBeNull(because: "I Just got it no?"); }); }
public static Task <AuthenticationResult> AcquireToken(MediaAccount mediaAccount) { string settingKey = Constant.AppSettingKey.DirectoryAuthorityUrl; string authorityUrl = AppSetting.GetValue(settingKey); authorityUrl = string.Format(authorityUrl, mediaAccount.DirectoryTenantId); string redirectUri = Constant.AuthIntegration.RedirectUri; ClientCredential clientCredential = new ClientCredential(mediaAccount.ServicePrincipalKey); ConfidentialClientApplication clientApplication = new ConfidentialClientApplication(mediaAccount.ServicePrincipalId, authorityUrl, redirectUri, clientCredential, null, null); settingKey = Constant.AppSettingKey.AzureResourceManagementTokenScope; string tokenScope = AppSetting.GetValue(settingKey); string[] tokenScopes = new string[] { tokenScope }; return(clientApplication.AcquireTokenForClientAsync(tokenScopes)); }
private static async Task <string> GetTokenForClientAsync() { // NOTE: You cannot use the common endpoint when using app-only permission. We need your tenant ID. var authority = $"https://login.microsoftonline.com/{TenantId}/v2.0"; var daemonClient = new ConfidentialClientApplication( ClientId, authority, ReplyUri, new ClientCredential(ClientSecret), null, null); // With app-only you cannot specify permission scopes on the fly. Only the default scope is accepted. string[] scopes = { "https://graph.microsoft.com/.default" }; var result = await daemonClient.AcquireTokenForClientAsync(scopes); return(result.AccessToken); }
/// <summary> /// Will acquire a token from the confidential client via the "Delegated" access or Elevated permission set /// </summary> /// <returns></returns> public async Task <string> GetGraphDaemonAccessTokenAsync() { var tenantId = ConfigKeys.TenantId; var iss = string.Format(ConstantsAuthentication.TenantAuthority, tenantId); var lowerscopes = new string[] { ConstantsAuthentication.MSGraphScope }; try { ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(ConfigKeys.MSALClientID, iss, ConfigKeys.PostLogoutRedirectURI, new ClientCredential(ConfigKeys.MSALClientSecret), null, new TokenCache()); AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(lowerscopes); return(authResult.AccessToken); } catch (Exception ex) { System.Diagnostics.Trace.TraceError($"Failed to claim credentials {iss} w/ {ex.Message}"); return(null); } }
private async Task <TokenTenant> GetGraphToken(string tenantId) { var token = new TokenTenant(); try { var daemonClient = new ConfidentialClientApplication(Startup.clientId, String.Format(Constant.authorityFormat, tenantId), Startup.redirectUri, new ClientCredential(Startup.clientSecret), null, new TokenCache()); var authResult = await daemonClient.AcquireTokenForClientAsync(new string[] { Constant.msGraphScope }); token.Token = authResult.AccessToken; } catch (Exception ex) { } return(token); }
public async Task ApplicationGrantIntegrationTestAsync() { var appCache = new TokenCache(); var userCache = new TokenCache(); var confidentialClient = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(_password), userCache, appCache); var res = await confidentialClient.AcquireTokenForClientAsync(MsalScopes).ConfigureAwait(false); Assert.IsNotNull(res); Assert.IsNotNull(res.AccessToken); Assert.IsNull(res.IdToken); Assert.IsNull(res.Account); // make sure user cache is empty Assert.IsTrue(userCache.TokenCacheAccessor.GetAllAccessTokensAsString().Count == 0); Assert.IsTrue(userCache.TokenCacheAccessor.GetAllRefreshTokensAsString().Count == 0); Assert.IsTrue(userCache.TokenCacheAccessor.GetAllIdTokensAsString().Count == 0); Assert.IsTrue(userCache.TokenCacheAccessor.GetAllAccountsAsString().Count == 0); // make sure nothing was written to legacy cache Assert.IsNull(userCache.LegacyCachePersistence.LoadCache()); // make sure only AT entity was stored in the App msal cache Assert.IsTrue(appCache.TokenCacheAccessor.GetAllAccessTokensAsString().Count == 1); Assert.IsTrue(appCache.TokenCacheAccessor.GetAllRefreshTokensAsString().Count == 0); Assert.IsTrue(appCache.TokenCacheAccessor.GetAllIdTokensAsString().Count == 0); Assert.IsTrue(appCache.TokenCacheAccessor.GetAllAccountsAsString().Count == 0); Assert.IsNull(appCache.LegacyCachePersistence.LoadCache()); // passing empty password to make sure that AT returned from cache confidentialClient = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential("wrong_password"), userCache, appCache); res = await confidentialClient.AcquireTokenForClientAsync(MsalScopes).ConfigureAwait(false); Assert.IsNotNull(res); Assert.IsNotNull(res.AccessToken); Assert.IsNull(res.IdToken); Assert.IsNull(res.Account); }
public async Task <AccessTokenResult> GetAccessToken() { var cacheKey = "_GraphToken"; var graphToken = _memoryCacheManager.Get <AccessTokenResult>(cacheKey); if (!string.IsNullOrEmpty(graphToken?.Access_Token)) { return(graphToken); } var clientCredentials = new ClientCredential(_client_secret); var app = new ConfidentialClientApplication(_client_id, $"{_host}/{_tenant}", "https://graph.microsoft.com", clientCredentials, null, new TokenCache()); // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator var scopes = new string[] { _scope }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClientAsync(scopes); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected } var token = new AccessTokenResult { Access_Token = result.AccessToken, Expires_In = result.ExpiresOn.ToString(), }; var cacheTime = result.ExpiresOn - DateTime.UtcNow; //cacheTime = TimeSpan.FromMinutes(5); _memoryCacheManager.Set(cacheKey, token, cacheTime); return(token); }
private async Task <string> GetAccessToken() { ClientCredential clientCredentials = new ClientCredential(secret: config.AppSecret); var app = new ConfidentialClientApplication( clientId: config.AppId, authority: $"https://login.microsoftonline.com/{config.TenantId}", redirectUri: "https://daemon", clientCredential: clientCredentials, userTokenCache: null, appTokenCache: new TokenCache() ); string[] scopes = new string[] { "https://graph.microsoft.com/.default" }; var result = await app.AcquireTokenForClientAsync(scopes); return(result.AccessToken); }
private static HttpClient GetAuthenticatedHTTPClient(IConfigurationRoot config) { var clientId = config["applicationId"]; var clientSecret = config["applicationSecret"]; var redirectUri = config["redirectUri"]; var authority = $"https://login.microsoftonline.com/{config["tenantId"]}/v2.0"; List <string> scopes = new List <string>(); scopes.Add("https://graph.microsoft.com/.default"); var cca = new ConfidentialClientApplication(clientId, authority, redirectUri, new ClientCredential(clientSecret), null, null); var authResult = cca.AcquireTokenForClientAsync(scopes).Result; _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Add("Authorization", "bearer " + authResult.AccessToken); return(_httpClient); }
public static async Task DamonLogInAsync() { AuthenticationResult result; var daemonClient = new ConfidentialClientApplication( clientId , string.Format(AuthorityFormat, tenantId) , redirectUri , new ClientCredential(clientSecret) , cliTokenCache.GetMsalCacheInstance() , appTokenCache.GetMsalCacheInstance() ); try { result = await daemonClient.AcquireTokenForClientAsync(new[] { MSGraphScope }); //Console.WriteLine(result.AccessToken); graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async(requestMessage) => { // Append the access token to the request. requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken); // Some identifying header requestMessage.Headers.Add("SampleID", "aspnet-connect-sample"); } ) ); TokenAcquired = DateTime.Now; } // Unable to retrieve the access token silently. catch (Exception e) { Console.WriteLine(e.Message); logger.Error(e.Message); } }
public async Task HttpRequestExceptionIsNotSuppressed() { var app = new ConfidentialClientApplication(TestConstants.ClientId, TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret), new TokenCache(), new TokenCache()) { ValidateAuthority = false }; // add mock response bigger than 1MB for Http Client HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler { Method = HttpMethod.Get, ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(new string(new char[1048577])) } }); await app.AcquireTokenForClientAsync(TestConstants.Scope.ToArray()); }
private async Task <DemoModel> GetDemoPageModel(string apiBaseUrl) { var model = new DemoModel(); try { var app = new ConfidentialClientApplication( _appSettings.ClientId, _appSettings.EmployeeApiAuthority, "https://localhost", // redirect URI can be anything in this case new ClientCredential(_appSettings.ClientSecret), userTokenCache: null, appTokenCache: new TokenCache()); var authRes = await app.AcquireTokenForClientAsync( new[] { _appSettings.EmployeeApiAppIdUri + "/.default" }, true); model.AccessToken = authRes.AccessToken; var req = new HttpRequestMessage(HttpMethod.Get, apiBaseUrl + "/api/employees"); model.TargetUrl = req.RequestUri.ToString(); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authRes.AccessToken); var res = await HttpClient.SendAsync(req); if (res.IsSuccessStatusCode) { model.Employees = await res.Content.ReadAsAsync <List <Employee> >(); } else { model.ErrorStatusCode = res.StatusCode; } } catch { } return(model); }
static async Task <string> AccessToken(IConfiguration config) { var client = new ConfidentialClientApplication( clientId: config["ClientID"], authority: $"https://login.microsoftonline.com/{config["TenantID"]}/", redirectUri: config["ClientRedirectUri"], clientCredential: new ClientCredential(config["ClientSecret"]), userTokenCache: null, appTokenCache: null); try { var result = await client.AcquireTokenForClientAsync(new[] { "https://graph.microsoft.com/.default" }); return(result.AccessToken); } catch (Exception e) { Log(e.ToString(), ConsoleColor.Red); throw; } }
// Gets an access token. First tries to get the access token from the token cache. // This app uses a password (secret) to authenticate. Production apps should use a certificate. public async Task <string> GetAppAccessTokenAsync() { try { var authorityFormat = "https://login.microsoftonline.com/{0}/v2.0"; ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(_clientId, String.Format(authorityFormat, _tenantId), _redirectUri, _credential, null, new TokenCache()); var msGraphScope = "https://graph.microsoft.com/.default"; AuthenticationResult result = await daemonClient.AcquireTokenForClientAsync(new string[] { msGraphScope }); return(result.AccessToken); } catch (Exception ex) { // Unable to retrieve the access token silently. throw new ServiceException(new Error { Code = GraphErrorCode.AuthenticationFailure.ToString(), Message = $"Caller needs to authenticate. Unable to retrieve the access token silently. error: {ex}" }); } }
// GET api/<controller> public async Task <IEnumerable <string> > Get() { var tenantId = ClaimsPrincipal.Current.FindFirst(tenantIdClaimType).Value; ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(Startup.clientId, String.Format(authorityFormat, tenantId), Startup.redirectUri, new ClientCredential(Startup.clientSecret), null, new TokenCache()); AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(new string[] { msGraphScope }); // Query for list of users in the tenant HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, msGraphQuery); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); HttpResponseMessage response = await client.SendAsync(request); // If the token we used was insufficient to make the query, drop the token from the cache. // The Users page of the website will show a message to the user instructing them to grant // permissions to the app (see User/Index.cshtml). if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) { // BUG: Here, we should clear MSAL's app token cache to ensure that on a subsequent call // to SyncController, MSAL does not return the same access token that resulted in this 403. // By clearing the cache, MSAL will be forced to retrieve a new access token from AAD, // which will contain the most up-to-date set of permissions granted to the app. Since MSAL // currently does not provide a way to clear the app token cache, we have commented this line // out. Thankfully, since this app uses the default in-memory app token cache, the app still // works correctly, since the in-memory cache is not persistent across calls to SyncController // anyway. If you build a persistent app token cache for MSAL, you should make sure to clear // it at this point in the code. // //daemonClient.AppTokenCache.Clear(Startup.clientId); } if (!response.IsSuccessStatusCode) { throw new HttpResponseException(response.StatusCode); } return(null); }
public async Task RunAsync() { var tenantId = Config.GetConfig("tenantId"); ConfidentialClientApplication daemonClient = new ConfidentialClientApplication( Config.GetConfig("clientId"), String.Format(Config.GetConfig("authorityFormat"), tenantId), Config.GetConfig("replyUri"), new ClientCredential(Config.GetConfig("clientSecret")), null, new TokenCache()); var authenticationResult = await daemonClient.AcquireTokenForClientAsync(new string[] { "https://graph.microsoft.com/.default" }); var accessToken = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://graph.microsoft.com/beta/"); client.DefaultRequestHeaders.Authorization = accessToken; await DemoBatch(client); } }