2015-09-10 55 views
1

我已經創建了一個應用程序與用戶的asp.net mvc api,跟隨this tutorial。一切都很好。本地用戶和Facebook登錄工作正常。asp.net mvc API獲取Facebook令牌

但現在我試圖使用FacebookClient並獲取用戶信息和朋友。 但它詢問我的令牌,但不是存儲在我的會話或cookie上的相同標記。

在API控制器帳戶,在GetExternalLogin行動我有這樣的代碼:

if (hasRegistered) 
      { 
       Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 

       ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, 
        OAuthDefaults.AuthenticationType); 
       ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, 
        CookieAuthenticationDefaults.AuthenticationType); 

       AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 
       Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); 
      } 
      else 
      { 
       IEnumerable<Claim> claims = externalLogin.GetClaims(); 
       ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); 
       Authentication.SignIn(identity); 
      } 

在這裏我能找到的索賠。但不是如何使用這個

我的問題是如何在登錄後在我的api上存儲Facebook令牌?

+0

由於很長一段時間你發佈這些問題,你有沒有找到如何將用戶/登錄/索賠保存在數據庫。如果用戶已經註冊,該如何處理。 –

回答

1
var options = new FacebookAuthenticationOptions 
{ 
    AppId = "Your App ID", 
    AppSecret = "Your App Secret", 
    Provider = new FacebookAuthenticationProvider 
    { 
     OnAuthenticated = async context => 
     { 
      // Retrieve the OAuth access token to store for subsequent API calls 
      string accessToken = context.AccessToken; 

      // Retrieve the username 
      string facebookUserName = context.UserName; 

      // You can even retrieve the full JSON-serialized user 
      var serializedUser = context.User; 
     } 
    } 
}; 

app.UseFacebookAuthentication(options); 

有關如何做到這一點的東西更多信息請看這裏:http://www.oauthforaspnet.com/providers/facebook/ F中的OnAuthenticated你還可以添加:

context.Identity.AddClaim(new Claim("FacebookToken", accessToken)); 

正如我敢肯定,在這一點上,我們已經創建了用戶並創建了他們的索賠,所以你

+0

是的,它有幫助,但索賠沒有保存。當我在context.Identity.AddClaim(新聲明(「FacebookToken」,accessToken))中放置一個斷點時;並複製AccessToken並手動使用它我可以使用它。我怎樣才能得到這個說法? – BrunoRamalho

+0

如果你想保存訪問令牌,你可以使用(我認爲)Id來搜索你在存儲機制中保存的客戶端。如果沒有用戶存在,您可以創建一個關聯到facebook並將代碼存儲在assosication表中。 我的意思是,您將用戶保存爲一條記錄,並將facebook用戶名+鏈接另存到另一條記錄中,以便您可以爲一位用戶進行多次登錄。 –

+0

如果您使用ASP.NET身份,您可以修改AspNetUserLogins表,以便在auth時包含ApiAccessCode,但我確信ASP.NET身份應該已經進入到AspNetUserLogins表中,因此您只需查看條目並添加代碼 –