2016-03-14 65 views
0

我如何檢查,如果我有一個用戶名/密碼或與Facebook的身份驗證登錄?確定是否使用用戶名和密碼或登錄Facebook在ASP.Net MVC

我想有說像

if (loggedInWithUserNamePassword()) { 
    // show change password screen 
} else { // logged in with Facebook 
    // don't show change password screen 
} 

我期待通過條件「用戶」。和「請求」。爲使用選項,但似乎沒有任何跡象表明我登錄Facebook或沒有明確的跡象。

回答

0

Assuing你已經了Facebook的API連接和啓動和運行。 將FaceBook api連接命名爲變量FB。這是你如何檢查。

FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 
    // the user is logged in and has authenticated your 
    // app, and response.authResponse supplies 
    // the user's ID, a valid access token, a signed 
    // request, and the time the access token 
    // and signed request each expire 
    var uid = response.authResponse.userID; 
    var accessToken = response.authResponse.accessToken; 
    } else if (response.status === 'not_authorized') { 
    // the user is logged in to Facebook, 
    // but has not authenticated your app 
    } else { 
    // the user isn't logged in to Facebook. 
    } 
}); 

所以是的,這是一個JS調用,目前FB不支持getLoginStatus爲C#API實現,但是您可以隨時返回一個異步結果到服務器呼叫與JS響應,並在那裏工作的方式。

+0

我需要在頁面上:無論你想這樣

public static bool IsSignedInWithFacebook(this IIdentity identity) { // since the Facebook authentication handler add following claim // we could check to see if user has this claim or not var claimIdent = identity as ClaimsIdentity; return claimIdent != null && claimIdent.HasClaim(c => c.Type == "urn:facebook:name"); } 

現在使用這個擴展方法檢查我沒有調用任何Facebook API,所以這不適用於我的場景 – user1186050

0

我找到了一個解決方案,但它不是我要找的......

在ApplicationUser我創建了一個名爲

public bool IsSocialAccount {get; set}; 

領域,當我創建帳戶,如果從用戶名/密碼的值爲false,否則爲true。

然後我可以在我的controlller chcek這一點。

我一直在尋找一種更內置的方法來檢查,但是這會做

+0

每當用戶登錄時,如何在客戶端中存儲cookie? –

0

如果帳戶只被用社會登錄時使用ApplicationUser.PasswordHash將是無效的。所以如果你假定所有賬戶只有一個登錄機制(用戶名/密碼或社交登錄),那麼這應該能夠分辨出這兩者之間的關係。

如果允許使用相同的賬戶(這是由ASP.NET身份支持)多次登錄機制,你需要一個不同的方法。

+0

當你說「允許多個登錄機制」時,你是什麼意思?現在我有用戶名/密碼,Facebook和我有谷歌設置,但我已禁用它。因此Google將是唯一登錄的其他方法。 – user1186050

+0

可以設置一些東西,例如,用戶可以使用用戶名/密碼或Facebook登錄到同一個用戶。因此,當他們登錄進行特定會話時,他們可以使用他們的用戶名/密碼或Facebook,並且使用相同的ASP.NET身份登錄。該AddLoginAsync是ASP.NET身份API,可以讓你增加額外的方式來登錄。 – DavidS

+0

我沒有看到ApplicationUser爲PaswordHash任何靜態方法? – user1186050

0

如果您正在使用Microsoft.Owin.Security.Facebook NuGet包來從Facebook認證用戶,你可以檢查用戶宣稱,以確定他們是如何進行身份驗證。要做到這一點只需編寫一個擴展方法來檢查用戶是否簽署通過Facebook或不:

if(User.Identity.IsSignedInWithFacebook()) 
{ 
    // do what you want 
} 
相關問題