繁体   English   中英

确定是使用用户名和密码还是使用ASP.Net MVC中的Facebook登录

[英]Determine if logged in with username and password or with Facebook in ASP.Net MVC

如何检查我是否使用用户名/密码或Facebook身份验证登录?

我想说一个类似

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

我正在浏览“用户”。 和“请求”。 有关使用选项的信息,但似乎没有任何迹象表明我是否已使用Facebook登录。

确保您已经连接了Facebook的API并可以运行。 将FaceBook api连接命名为Variable 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不支持C#API实现的getLoginStatus,但是您始终可以将带有JS响应的异步结果返回到您的服务器调用中,并在其中进行操作。

我找到了解决方案,尽管这不是我想要的...

在ApplicationUser中,我创建了一个名为

public bool IsSocialAccount {get; set};

当我创建帐户时,如果通过用户名/密码创建的帐户值为false,否则为true。

然后,我可以在我的控制器中检查它。

我一直在寻找一种更内置的检查方法,但是这样做

如果该帐户仅用于社交登录,则ApplicationUser.PasswordHash将为null。 因此,如果您假设所有帐户都只有一个登录机制(用户名/密码或社交登录名),那么这应该能够在两者之间进行区分。

如果您允许同一帐户使用多种登录机制(ASP.NET Identity支持),则需要使用其他方法。

如果您使用Microsoft.Owin.Security.Facebook NuGet包从Facebook认证用户,则可以检查用户声明以确定他们的认证方式。 为此,只需编写扩展方法来检查用户是否通过Facebook登录:

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");
}

现在,您可以在任何需要的地方使用这种扩展方法:

if(User.Identity.IsSignedInWithFacebook())
{
    // do what you want
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM