public static string GetAccessToken(string resource) { // 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(resource, clientCredential, userIdentifier); // obtain access token return authResult.AccessToken; }
//string graphResourceId = "https://SharePointConfessions.sharepoint.com/"; // https://SharePointConfessions.sharepoint.com/ public void ConfigureAuth(IAppBuilder app) { ApplicationDbContext db = new ApplicationDbContext(); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = Authority, PostLogoutRedirectUri = postLogoutRedirectUri, Notifications = new OpenIdConnectAuthenticationNotifications() { // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. AuthorizationCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID)); AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); return Task.FromResult(0); } } }); }
public static ADALTokenCache GetTokenCache() { // get ClaimsPrincipal for current user ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current; string signedInUserID = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value; string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; ApplicationDbContext db = new ApplicationDbContext(); ADALTokenCache userTokenCache = new ADALTokenCache(signedInUserID); return userTokenCache; }