2016-09-28 68 views
2

試圖逆向工程此示例app。只有我沒有創建自己的服務,只是試圖使用Microsoft Graph API獲取我的個人資料信息。獲取以下錯誤:AdalSilentTokenAcquisitionException:由於在緩存中找不到令牌,因此無法默認獲取令牌。調用方法AcquireToken

AdalSilentTokenAcquisitionException:無法默認獲取令牌,因爲在緩存中找不到令牌。調用方法AcquireToken

我很新,但我已經通過了所有與該錯誤相關的stackoverflow問題,一直沒能弄明白。

我正在使用Asp.net核心最新版本。 AcquireTokenSilentAsync上面的錯誤我總是失敗。任何提示或想法都會有所幫助。

以下是我到目前爲止。

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     app.UseApplicationInsightsRequestTelemetry(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseBrowserLink(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     app.UseApplicationInsightsExceptionTelemetry(); 

     app.UseStaticFiles(); 

     app.UseSession(); 

     //app.UseCookieAuthentication(); 

     // Populate AzureAd Configuration Values 
     Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; 
     ClientId = Configuration["Authentication:AzureAd:ClientId"]; 
     ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"]; 
     GraphResourceId = Configuration["Authentication:AzureAd:GraphResourceId"]; 
     GraphEndpointId = Configuration["Authentication:AzureAd:GraphEndpointId"]; 

     // Configure the OWIN pipeline to use cookie auth. 
     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 

     app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions 
     { 
      ClientId = ClientId, 
      ClientSecret = ClientSecret, 
      Authority = Authority, 
      CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], 
      ResponseType = OpenIdConnectResponseType.CodeIdToken, 
      GetClaimsFromUserInfoEndpoint = false, 

      Events = new OpenIdConnectEvents 
      { 
       OnRemoteFailure = OnAuthenticationFailed, 
       OnAuthorizationCodeReceived = OnAuthorizationCodeReceived, 
      } 

     }); 

OnAuthorizationCodeReceived:

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context) 
    { 
     // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token to the Todo List API 
     string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; 
     ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret); 
     AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session)); 
     AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
      context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId); 

     // Notify the OIDC middleware that we already took care of code redemption. 
     context.HandleCodeRedemption(); 



    } 

MyProfileController:

public async Task<IActionResult> Index() 
    { 
     AuthenticationResult result = null; 
     var user = new ADUser(); 

     try 
     { 
      string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value; 
      AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session)); 
      ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret); 
      var tc = authContext.TokenCache.ReadItems(); 
      result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.RequiredDisplayableId)); 

      HttpClient client = new HttpClient(); 
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me"); 
      request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 
      HttpResponseMessage response = await client.SendAsync(request); 

      if (response.IsSuccessStatusCode) 
      { 
       String responseString = await response.Content.ReadAsStringAsync(); 
       List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>(); 
      } 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
     return View(); 
    } 

回答

1

我建議使用UserIdentifierType.UniqueId作爲樣本does。使用錯誤的標識符類型會導致緩存未命中。如果庫無法找到令牌緩存條目,則會因此錯誤而失敗,並且您需要讓用戶再次登錄。讓我知道你是否已經嘗試過,但沒有奏效。

+0

謝謝你回到我身邊。我試過了,但它仍然無法工作。然而,我注意到,如果我在這一行上放置一個斷點:result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId,credential,new UserIdentifier(userObjectID,UserIdentifierType.UniqueId));然後等待幾分鐘,代碼將繼續執行錯誤。 –

+0

您是否可以使用ADAL日誌和/或網絡跟蹤來更新問題?從ADAL收集日誌的臨時說明在這裏:https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/527。重要的網絡跟蹤將是login.microsoftonline.com的任何會話 – dstrockis

0

AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));

調試此行並檢查authContext緩存字典表中的數據。如果記錄爲0,則詢問/重定向用戶登錄。一旦用戶登錄緩存表應該被填充並且toke應該可用。

AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, 
         new NaiveSessionCache(userObjectID)); 
        if (authContext.TokenCache.Count == 0) 
        { 
         authContext.TokenCache.Clear(); 
         CosmosInterface.Utils.AuthenticationHelper.token = null; 
         HttpContext.GetOwinContext().Authentication.SignOut(
          OpenIdConnectAuthenticationDefaults.AuthenticationType, 
          CookieAuthenticationDefaults.AuthenticationType); 
        } 
相關問題