2017-02-04 128 views
0

我正在嘗試針對Microsoft權限使用OpenIdConnectAuthentication。我可以進行身份​​驗證,但是當嘗試獲取訪問令牌時,通話失敗,希望我重新進行身份驗證,而我卻這麼做。我似乎從來沒有拉適當的令牌。這是獲取訪問令牌的代碼。ConfidentialClientApplication AcquireTokenSilentAsync總是失敗

public async Task<string> GetUserAccessTokenAsync() 
{ 
    string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 
    //string signedInUserID = User.Identity.GetUserId(); 
    tokenCache = new MSALSessionCache(
     signedInUserID, 
     HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase); 
    var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache 

    ConfidentialClientApplication cca = new ConfidentialClientApplication(
     appId, 
     redirectUri, 
     new ClientCredential(appSecret), 
     tokenCache); 

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

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

     //throw new Exception("Resource.Error_AuthChallengeNeeded"); 
     return null; 
    } 
} 

我不知道我錯過了什麼。到目前爲止,我已經使用Microsoft Graph REST ASPNET Connect示例來指導我。我的最終目標是驗證用戶,然後使用他們的個人資料和MS休息API中的一些項目。

回答

0

我能夠跟蹤下來。因爲我使用的是Asp.net身份驗證和UseOpenIdConnectAuthentication,所以我必須手動將外部登錄聲明添加到ClaimsPrincipal。這個我什麼我ExternalLoginCallback(字符串RETURNURL)看起來像:

 public async Task<ActionResult> ExternalLoginCallback(string returnUrl) 
    { 
     var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 
     if (loginInfo == null) 
     { 
      return RedirectToAction("Login"); 
     } 

     // Sign in the user with this external login provider if the user already has a login 
     var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); 

     logger.Info(loginInfo.Email + " attempted an external login with a result of " + result.ToString()); 

     switch (result) 
     { 
      case SignInStatus.Success:     
       foreach (Claim c in loginInfo.ExternalIdentity.Claims) 
       { 
        SignInManager.AuthenticationManager.AuthenticationResponseGrant.Identity.AddClaim(new Claim(c.Type + "_external", c.Value)); 
       } 

       var user = UserManager.FindById(SignInManager.AuthenticationManager.AuthenticationResponseGrant.Identity.GetUserId()); 

       user.LastLogin = DateTime.Now.ToUniversalTime(); 
       await UserManager.UpdateAsync(user); 

       return RedirectToLocal(returnUrl); 
      case SignInStatus.LockedOut: 
       return View("Lockout"); 
      case SignInStatus.RequiresVerification: 
       return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); 
      case SignInStatus.Failure: 
      default: 
       // If the user does not have an account, then prompt the user to create an account 
       ViewBag.ReturnUrl = returnUrl; 
       ViewBag.LoginProvider = loginInfo.Login.LoginProvider; 
       return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); 
     } 
    } 

由於外部標識與相匹配的asp.net身份名稱的要求,我不得不重新命名的蛤蜊。然後還可以在代碼中隨時隨地調整以尋找外部身份聲明。