private static string GetAccessToken() { // get user ID in security cookie var signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; // get token cache for signed in user ApplicationDbContext db = new ApplicationDbContext(); ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID); AuthenticationContext authContext = new AuthenticationContext(Authority, userTokenCache); // Get credentials for user var clientCredential = new ClientCredential(clientId, clientSecret); // Create user identifier object using User ID for Azure Active Directory account string objectIdentifierID = "http://schemas.microsoft.com/identity/claims/objectidentifier"; var userObjectId = ClaimsPrincipal.Current.FindFirst(objectIdentifierID).Value; var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId); // call to ADAL to get access token from cache of across network var authResult = authContext.AcquireTokenSilent(urlMicrosoftGraphApiResource, clientCredential, userIdentifier); // obtain access token return authResult.AccessToken; }
private static async Task<string> GetAccessTokenAsync() { // determine authorization URL for current tenant string authorizationUrlRoot = ConfigurationManager.AppSettings["ida:AADInstance"]; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string authorizationUrlTenant = authorizationUrlRoot + 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(authorizationUrlTenant, userTokenCache); // determine the resources to be accessed string MicrosoftGraphApiResourceId = "https://graph.Microsoft.com"; // create client credential object using client ID and client secret string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"]; 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 Office 365 unifed API from AAD AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(MicrosoftGraphApiResourceId, clientCredential, userIdentifier); // return access token back to user return authenticationResult.AccessToken; }