/// <summary> /// 使用该方法获取Access Token /// </summary> /// <returns></returns> public async Task <string> GetUserAccesstokenAsync() { string singedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current); TokenCache userTokenCache = new TokenSessionCache(singedInUserID, httpContext) .GetMsalCacheInstance(); ConfidentialClientApplication cca = new ConfidentialClientApplication( ClientID, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null); string[] scopes = GraphScopes.Split(new char[] { ' ' }); try { AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());//confidential.Users.First()); return(result.AccessToken); } catch (Exception ex) { HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( new Microsoft.Owin.Security.AuthenticationProperties() { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); throw new ServiceException( new Error { Code = GraphErrorCode.AuthenticationFailure.ToString(), Message = Resource.Error_AuthChallengeNeeded, }); } }
/// <summary> /// 接收到Code /// </summary> /// <param name="context"></param> /// <returns></returns> private async Task AuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification context) { var code = context.Code; var signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; TokenCache tokenCache = new TokenSessionCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); ConfidentialClientApplication confidential = new ConfidentialClientApplication( ClientID, RedirectUri, new ClientCredential(ClientSecret), tokenCache, null); string[] scopes = GraphScopes.Split(new char[] { ' ' }); AuthenticationResult result = await confidential.AcquireTokenByAuthorizationCodeAsync(code, scopes); }
/// <summary> /// Retrieves the cached access token for the WebAPI. If an access token cannot be found in the /// cache, return an empty access token. /// </summary> /// <returns>WebAPI access token. Empty if a cached access token cannot be found.</returns> private async Task <string> GetAPIAccessToken(string scope) { string accessToken = string.Empty; // The cache is built using the signed in user's identity so we must retrieve their name identifier // from the claims collection string userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; // Reconstruct the token cache based on the signed in User ID and the current HttpContext TokenSessionCache tokenSessionCache = new TokenSessionCache(userId, this.HttpContext); List <TokenResult> tokenCache = tokenSessionCache.GetTokenCacheInstance(); TokenResult tokenResult = tokenCache.FirstOrDefault(t => t.scope.Contains(scope)); if (tokenResult == null) { // The token was not found in the cache, force a sign out of the user // so they must re-authenticate await HttpContext.SignOutAsync(); } else { // Check for access token expiration and get another using refresh token accessToken = tokenResult.access_token; DateTime expiresOn = _epoch + new TimeSpan(0, 0, tokenResult.expires_on); if (expiresOn < DateTime.UtcNow) { string authority = $"{_configuration.GetValue<string>("AzureADB2C:Instance")}tfp/{_configuration.GetValue<string>("AzureADB2C:Domain")}/{_configuration.GetValue<string>("AzureADB2C:SignUpSignInPolicyId")}"; TokenResult newTokenResult = await TokenHelper.GetAccessTokenByRefreshToken(authority, _configuration.GetValue <string>("AzureADB2C:ClientId"), _configuration.GetValue <string>("AzureADB2C:ClientSecret"), tokenResult.refresh_token, scope); accessToken = newTokenResult.access_token; // Update token cache for (int i = 0; i < tokenCache.Count; i++) { if (tokenCache[i].scope.Contains(scope)) { tokenCache[i] = newTokenResult; tokenSessionCache.Persist(); break; } } } } return(accessToken); }
private async Task <string> GetAccessTokens(string userId, HttpContext httpContext, string authorizationCode, string authority, string redirectUri, string clientId, string clientSecret, string scopes) { string accessToken = string.Empty; string refreshToken = string.Empty; TokenSessionCache tokenSessionCache = new TokenSessionCache(userId, httpContext); List <TokenResult> tokenCache = tokenSessionCache.GetTokenCacheInstance(); string[] apiScopes = scopes.Split(" "); if (apiScopes.Length > 0) { for (int i = 0; i < apiScopes.Length; i++) { if (i == 0) { TokenResult tokenResult = await TokenHelper.GetAccessTokenByAuthorizationCode(authority, clientId, clientSecret, authorizationCode, redirectUri, apiScopes[i]); tokenCache.Add(tokenResult); accessToken = tokenResult.access_token; refreshToken = tokenResult.refresh_token; } else { if (!string.IsNullOrEmpty(refreshToken)) { TokenResult tokenResult = await TokenHelper.GetAccessTokenByRefreshToken(authority, clientId, clientSecret, refreshToken, apiScopes[i]); tokenCache.Add(tokenResult); } } } } if (tokenCache.Count > 0) { tokenSessionCache.Persist(); } return(accessToken); }