// 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; tokenCache = new SessionTokenCache( signedInUserID, HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase); //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache ConfidentialClientApplication cca = new ConfidentialClientApplication( appId, redirectUri, new ClientCredential(appSecret), tokenCache); try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' })); return result.Token; } // Unable to retrieve the access token silently. catch (MsalSilentTokenAcquisitionException) { HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( new AuthenticationProperties() { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); throw new Exception(Resource.Error_AuthChallengeNeeded); } }
// Here we clear the token cache and end the session with the web app. public void SignOut() { if (Request.IsAuthenticated) { // Get the user's token cache and clear it. string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext); tokenCache.Clear(userObjectId); } // Send an OpenID Connect sign-out request. HttpContext.GetOwinContext().Authentication.SignOut( CookieAuthenticationDefaults.AuthenticationType); Response.Redirect("/"); }