2015-10-07 174 views
2

我已經實現了下面的示例以下天青AD AUTH:ADAL令牌獲取異常

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect

這裏是從我的應用程序的代碼。用戶正在收到間歇性異常「靜默獲取令牌失敗。調用方法令牌獲取」。任何幫助將不勝感激。

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions 
     { 
      ClientId = ClientId, 
      Authority = Authority, 

      Notifications = new OpenIdConnectAuthenticationNotifications() 
      { 
       AuthorizationCodeReceived = (context) => 
       { 
        string userObjectId = null; 
        var code = context.Code; 

        var currentClaimsIdentity = context.AuthenticationTicket.Identity; 
        if (currentClaimsIdentity != null) 
        { 
         userObjectId = currentClaimsIdentity.FindFirst(Constants.ObjectIdentifierClaimType).Value; 
        } 

        ClientCredential credential = new ClientCredential(ClientId, AppKey); 
        AuthenticationContext authContext = new AuthenticationContext(Authority, new SessionCache(userObjectId, HttpContext.Current)); 
        authContext.AcquireTokenByAuthorizationCode(code, StandardSettings.ReplyUrl, credential, Constants.GraphResourceBaseUrl); 

        return Task.FromResult(0); 
       }, 

       AuthenticationFailed = context => 
       { 
        context.HandleResponse(); 
        context.Response.Redirect("/"); 

        return Task.FromResult(0); 
       } 
      } 
     }); 



/// <summary> 
    /// Gets the access token. 
    /// </summary> 
    /// <returns>The access token for service call.</returns> 
    private string GetAccessToken() 
    { 
     string userName = null; 
     AuthenticationResult authenticationResult = null; 

     ClaimsPrincipal currentClaimsPrincipal = ClaimsPrincipal.Current; 
     if (currentClaimsPrincipal != null) 
     { 
      userName = currentClaimsPrincipal.FindFirst(ClaimTypes.Name).Value; 
     } 

     try 
     { 
      authenticationResult = this.GetAuthenticationResult(); 

      if (authenticationResult.ExpiresOn < DateTimeOffset.UtcNow) 
      { 
       Trace.TraceWarning("Access token expired for the user: {0}. Challenge the user authentication to get a new token.", userName); 
       this.httpCurrentContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); 
      } 
     } 
     catch (AdalSilentTokenAcquisitionException ex) 
     { 
      Trace.TraceWarning("Failed to acquire the token for the user: {0} with exception: {1}. Challenge the user authentication for retry.", userName, ex); 
      this.httpCurrentContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); 
     } 

     if (authenticationResult == null) 
     { 
      try 
      { 
       authenticationResult = this.GetAuthenticationResult(); 
      } 
      catch (Exception ex) 
      { 
       Trace.TraceWarning("Failed to acquire the token on the retry for the user: {0} with the exception: {1}.", userName, ex); 
       throw new AdalException(
        AdalError.FailedToAcquireTokenSilently, 
        "The session expired or the token cache was reset. Please sign out and then navigate to the url again to re-authenticate."); 
      } 
     } 

     return authenticationResult.AccessToken; 
    } 

    /// <summary> 
    /// Get the authentication result for the request. 
    /// </summary> 
    /// <returns>The authentication result.</returns> 
    private AuthenticationResult GetAuthenticationResult() 
    { 
     string userObjectId = null; 

     ClaimsPrincipal currentClaimsPrincipal = ClaimsPrincipal.Current; 
     if (currentClaimsPrincipal != null) 
     { 
      userObjectId = currentClaimsPrincipal.FindFirst(Constants.ObjectIdentifierClaimType).Value; 
     } 

     AuthenticationContext authContext = new AuthenticationContext(
        Startup.Authority, 
        new SessionCache(userObjectId, this.httpCurrentContext)); 

     ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.AppKey); 
     return authContext.AcquireTokenSilent(
      Constants.GraphResourceBaseUrl, 
      credential, 
      new UserIdentifier(userObjectId, UserIdentifierType.UniqueId)); 
    } 

回答

2

該消息出現的原因有多種:

  • 您正在使用的高速緩存爲空
  • 緩存不包含有效的刷新令牌(過期等)
  • 的緩存不包含您指定的權威/ clientid /用戶組合的刷新令牌
  • 用戶的標識符不對應於最初爲i的實際用戶標識符在令牌中搜索