2016-09-28 4 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

私はサンプルdoesとしてUserIdentifierType.UniqueIdを使用してお勧めします。誤った識別子タイプを使用すると、キャッシュミスが発生する可能性があります。ライブラリがトークンキャッシュエントリを見つけることができない場合、このエラーで失敗し、再度サインインするようにユーザーに依頼する必要があります。あなたがすでにそれを試しても動作しなかったら私に知らせてください。

+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、 新しい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); 
        } 
関連する問題