2016-02-03 77 views
3

我一直在關注webapi oauth登錄這裏的教程;WebApi 2 OAuth外部登錄訪問令牌問題

http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-angularjs-app/

這一切運行順利,但我有檢索從外部供應商發回的令牌(在這種情況下,測試谷歌)的困難。

因此,在用戶驗證並確認登錄後,「ExternalLogin」在Webapi上第二次終止了帶有驗證數據。

在這種方法

它調用下面的所有數據中提取的一類

ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 

它在這裏,它似乎是掉落。當它調用FromIdentity方法時;

public static ExternalLoginData FromIdentity(ClaimsIdentity identity) 
    { 
     if (identity == null) 
     { 
      return null; 
     } 

     Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); 

     if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value)) 
     { 
      return null; 
     } 

     if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) 
     { 
      return null; 
     } 

     return new ExternalLoginData 
     { 
      LoginProvider = providerKeyClaim.Issuer, 
      ProviderKey = providerKeyClaim.Value, 
      UserName = identity.FindFirstValue(ClaimTypes.Name), 
      ExternalAccessToken = identity.FindFirstValue("ExternalAccessToken"), 
     }; 
    } 

該行;

ExternalAccessToken = identity.FindFirstValue("ExternalAccessToken") 

返回爲空?我無法看到這個令牌在任何索賠中被返回?

+0

於是在課上「GoogleAuthProvider」它實現了「IGoogleOAuth2AuthenticationProvider」,如果你在通過身份驗證的情況下發送的突破點,是你能夠檢查「context.AccessToken」的價值?如果不是您使用的MS.Owin.Security版本是什麼?你可以嘗試回退並使用本文中使用的相同版本,如果它工作的話,嘗試升級軟件包並監控結果。 –

+0

嗨Taiseer,謝謝你的回覆。是的,它看起來可能已經下降到Nuget軟件包的不良安裝。感謝您指出令牌的分配位置。 'Authenticated'方法不會觸發並設置外部訪問令牌。我用以下版本執行了nuget軟件包的重新安裝; Google.Apis.Oauth2.v2客戶端庫1.10.0.1000 –

回答

1

ExternalAccessToken是添加的自定義聲明。請檢查以下來自默認提供者的代碼。

對於谷歌

public class GoogleAuthProvider : IGoogleOAuth2AuthenticationProvider 
    { 
     public void ApplyRedirect(GoogleOAuth2ApplyRedirectContext context) 
     { 
      context.Response.Redirect(context.RedirectUri); 
     } 

     public Task Authenticated(GoogleOAuth2AuthenticatedContext context) 
     { 
      context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); 
      return Task.FromResult<object>(null); 
     } 

     public Task ReturnEndpoint(GoogleOAuth2ReturnEndpointContext context) 
     { 
      return Task.FromResult<object>(null); 
     } 
    } 

對於Facebook的

public class FacebookAuthProvider : FacebookAuthenticationProvider 
    { 
     public override Task Authenticated(FacebookAuthenticatedContext context) 
     { 
      context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); 
      return Task.FromResult<object>(null); 
     } 
    } 

在這些類中加入使用下面的行的要求;

context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));