2017-05-10 10 views
0

Microsoft Graph APIを使用してASP.NET MVCプロジェクトを作成しています。これは、サンプルコードhttps://github.com/microsoftgraph/aspnet-snippets-sampleに大きく基づいています。アプリはまずうまく動作します。テナントアカウントを使用してログインし、グラフからデータを取得できます。しかし、我々は、Visual Studioからの新しいセッションを開始するか、私達はちょうどしばらく待っていれば、AcquireTokenSilentAsyncトークンを静かに取得できませんでした - Microsoft Graph API

をスローした場合は、Webブラウザのキャッシュがクリアされている場合は、それが再び動作するトークン黙っ

の取得に失敗しましたが、しばらくするとエラーが返されます。 一般、組織、テナントに権限を変更しようとしましたが、エラーが残ります。アクセストークンを取得するための

私たちの方法は次のとおりです。

// Gets an access token and its expiration date. First tries to get the token from the token cache. 
    public async Task<string> GetUserAccessTokenAsync() 
    { 
     // Initialize the cache. 
     HttpContextBase context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase; 

     tokenCache = new SessionTokenCache(
      ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value, 
      context); 
     IEnumerable<TokenCacheItem> cachedItems = tokenCache.ReadItems(appId); // see what's in the cache 
     if (cachedItems.Count() > 0) 
      return cachedItems.First().Token; 

     if (!redirectUri.EndsWith("/")) redirectUri = redirectUri + "/"; 
     string[] segments = context.Request.Path.Split(new char[] { '/' }); 
     ConfidentialClientApplication cca = new ConfidentialClientApplication(
      appId, 
      redirectUri + segments[1], 
      new ClientCredential(appSecret), 
      tokenCache); 

     string allScopes = nonAdminScopes; 
     string[] scopes = allScopes.Split(new char[] { ' ' }); 
     try 
     { 
      AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes); 
      return result.Token; 
     } 

     // Unable to retrieve the access token silently. 
     catch (MsalSilentTokenAcquisitionException) 
     { 
      HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
       new AuthenticationProperties() { RedirectUri = redirectUri + segments[1] }, 
       OpenIdConnectAuthenticationDefaults.AuthenticationType); 

      throw new ServiceException(
       new Error 
       { 
        Code = GraphErrorCode.AuthenticationFailure.ToString(), 
        Message = Resource.Error_AuthChallengeNeeded, 
       }); 
     } 
    } 

トークンは黙って取得することができない理由を任意のアイデア?

答えて

1

スローされた例外をどのように処理しますか?あなたが提供したサンプルでは、​​try/catchでエラーを処理し、例外が発生してエラーメッセージが一致すると、空の結果が返されます。この要求は、OpenIdミドルウェアによって傍受されます(..GetOwinContext()、Authentication.Challenge()はレスポンスコードを401に、認証タイプをOpenIdConnectAuthenticationDefaults.AuthenticationTypeに設定します)。

 try 
     { 

      // Initialize the GraphServiceClient. 
      GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient(); 

      // Get the files and folders in the current user's drive. 
      results.Items = await filesService.GetMyFilesAndFolders(graphClient); 
     } 
     catch (ServiceException se) 
     { 
      if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult(); 
      return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) }); 
     } 
関連する問題