当使用Facebook JS SDK从Facebook注销时,getLoginStatus返回状态未知 [英] getLoginStatus returns status unknown when trying to logout from Facebook using Facebook JS SDK

查看:1098
本文介绍了当使用Facebook JS SDK从Facebook注销时,getLoginStatus返回状态未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



启动配置类

p>

  public class ExternalLoginConfig 
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = ConfigSettings.FacebookAppId,
AppSecret = ConfigSettings.FacebookAppSecret,
Scope = {email },
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = context =>
{
var accessToken = context.AccessToken;
var facebookClient = new FacebookClient(accessToken);

var result = facebookClient.Get(me,new {fields =email,first_name,last_name})作为JsonObject;

string email = null;
string firstName = null;
string lastName = null;

if(result!= null)
{
email = result.ContainsKey(email)? (string)result [email]:null;
firstName = result.ContainsKey(first_name)? (string)result [first_name]:null;
lastName = result.ContainsKey(last_name)? (string)result [last_name]:null;
}

if(firstName!= null)
{
context.Identity.AddClaim(new Claim(ClaimTypes.GivenName,firstName));
}
if(lastName!= null)
{
context.Identity.AddClaim(new Claim(claimTypes.Surname,lastName));
}
if(email!= null)
{
context.Identity.AddClaim(new Claim(claimTypes.Email,email));
}

返回Task.FromResult(0);
},
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri +& auth_type = reauthenticate);
}
}
};
app.UseFacebookAuthentication(facebookAuthenticationOptions);
}
}

操作表单认证控制器


  [HttpPost] 
[AllowAnonymous]
public virtual ActionResult Login(string provider,string returnUrl)
{
ControllerContext.HttpContext.Session.RemoveAll();

return new ExternalLoginResult(provider,
Url.Action(LoginCallback,Oauth,new {ReturnUrl = returnUrl}));
}

[AllowAnonymous]
public async任务< ActionResult> LoginCallback(string returnUrl,string error)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

if(loginInfo == null)
{
return Redirect(returnUrl);
}

用户user = null;
string userName = Guid.NewGuid()。ToString();
string firstName = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.GivenName);
string lastName = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Surname);
string email = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Email);
string externalProviderName = loginInfo.Login.LoginProvider;
string externalProviderKey = loginInfo.Login.ProviderKey;

var externalAuthenticationInfo = new ExternalAuthenticationInfo()
{
用户名=用户名,
电子邮件=电子邮件,
FirstName = firstName,
LastName = lastName,
ExternalProviderName = externalProviderName,
ExternalProviderKey = externalProviderKey
};

var loginResult = userProvider.ExternalLogin(externalProviderKey,email,out user);

switch(loginResult)
{
case LoginResult.Success:
{
AuthenticationHelper.SetAuthenticatedUserId(user.ID);
break;
}
case LoginResult.NotRegistered:
{
var registerResult = userProvider.Register(userName,email,null,externalAuthenticationInfo);

if(registerResult.IsValid)
{
AuthenticationHelper.SetAuthenticatedUserId(registerResult.Result.ID);
}

break;
}
}

返回重定向(returnUrl);
}

Facebook JS SDK初始化

  window.fbAsyncInit = function(){
FB.init({
appId:'@ ConfigSettings.FacebookAppId'
xfbml:true,
version:'v2.4'
});
};

(function(d,s,id){
var js,fjs = d.getElementsByTagName(s)[0];
if(d.getElementById(id) {return;}
js = d.createElement(s); js.id = id;
js.src =//connect.facebook.net/en_US/sdk.js;
fjs.parentNode.insertBefore(js,fjs);
}(document,'script','facebook-jssdk'));

我正在尝试使用Facebook JS SDK将用户记录在Facebook之外,但是调用: / p>

  FB.getLoginStatus(function facebookLogoutCallback(facebookResponse){
if(facebookResponse.status!=='connected'){
return;
}

FB.logout(facebookLogoutCallback);
});

导致状态未知而不是 connected ,它在 facebookResponse 对象中返回。我还试图调用 FB.logout()而不使用如果语句,但它没有起作用。 / p>

也许你可以说,这种行为是由未经授权的用户状态引起的,但服务器端登录后,用户实际上登录了:在我的网站和Facebook上。 p>

解决方案

FB.logout函数中似乎有一个错误。调用它之后,用户不能再使用JS SDK登录此应用程序,因为FB.login函数返回

Object {status =unknown,authResponse = null}



编辑:

发现在FB.logout()之后创建一个名为fblo_ *的cookie,这似乎是其原因。我不明确为什么它在那里,它做什么,但删除它使登录工作再次。



因此,我创建了一个小脚本,寻找这个cookie和在我调用FB.login()之前删除它,您可能希望在点击事件中调用它( https://developers.facebook.com/docs/reference/javascript/FB.login/v2.5 )。

  function delete_cookie(name)
{
document.cookie = name +'=; expires = Thu,1970年1月01日00:00:01 GMT;路径= /;
}


var cookies = document.cookie.split(;);
(var i = 0; i< cookies.length; i ++)
{
if(cookies [i] .split(=)[0] .indexOf(fblo_ )!= -1)
delete_cookie(cookies [i] .split(=)[0]);
}


I have a localhost website, where I've implemented login via Facebook using Facebook C# SDK.

Startup configuration class:

public class ExternalLoginConfig
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
        {
            AppId = ConfigSettings.FacebookAppId,
            AppSecret = ConfigSettings.FacebookAppSecret,
            Scope = { "email" },
            Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = context =>
                {
                    var accessToken = context.AccessToken;
                    var facebookClient = new FacebookClient(accessToken);

                    var result = facebookClient.Get("me", new { fields = "email,first_name,last_name" }) as JsonObject;

                    string email = null;
                    string firstName = null;
                    string lastName = null;

                    if (result != null)
                    {
                        email = result.ContainsKey("email") ? (string) result["email"] : null;
                        firstName = result.ContainsKey("first_name") ? (string) result["first_name"] : null;
                        lastName = result.ContainsKey("last_name") ? (string) result["last_name"] : null;
                    }

                    if (firstName != null)
                    {
                        context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, firstName));
                    }
                    if (lastName != null)
                    {
                        context.Identity.AddClaim(new Claim(ClaimTypes.Surname, lastName));
                    }
                    if (email != null)
                    {
                        context.Identity.AddClaim(new Claim(ClaimTypes.Email, email));
                    }

                    return Task.FromResult(0);
                },
                OnApplyRedirect = context =>
                {
                    context.Response.Redirect(context.RedirectUri + "&auth_type=reauthenticate");
                }
            }
        };
        app.UseFacebookAuthentication(facebookAuthenticationOptions);
    }
}

Actions form Authentication controller:

[HttpPost]
[AllowAnonymous]
public virtual ActionResult Login(string provider, string returnUrl)
{
    ControllerContext.HttpContext.Session.RemoveAll();

    return new ExternalLoginResult(provider,
        Url.Action("LoginCallback", "Oauth", new { ReturnUrl = returnUrl }));
}

[AllowAnonymous]
public async Task<ActionResult> LoginCallback(string returnUrl, string error)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

    if (loginInfo == null)
    {
        return Redirect(returnUrl);
    }

    User user = null;
    string userName = Guid.NewGuid().ToString();
    string firstName = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.GivenName);
    string lastName = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Surname);
    string email = loginInfo.ExternalIdentity.FindFirstValue(ClaimTypes.Email);
    string externalProviderName = loginInfo.Login.LoginProvider;
    string externalProviderKey = loginInfo.Login.ProviderKey;

    var externalAuthenticationInfo = new ExternalAuthenticationInfo()
    {
        Username = userName,
        Email = email,
        FirstName = firstName,
        LastName = lastName,
        ExternalProviderName = externalProviderName,
        ExternalProviderKey = externalProviderKey
    };

    var loginResult = userProvider.ExternalLogin(externalProviderKey, email, out user);

    switch (loginResult)
    {
        case LoginResult.Success:
        {
            AuthenticationHelper.SetAuthenticatedUserId(user.ID);
            break;
        }
        case LoginResult.NotRegistered:
        {
            var registerResult = userProvider.Register(userName, email, null, externalAuthenticationInfo);

            if (registerResult.IsValid)
            {
                AuthenticationHelper.SetAuthenticatedUserId(registerResult.Result.ID);
            }

            break;
        }
    }

    return Redirect(returnUrl);
}

Facebook JS SDK initialization:

window.fbAsyncInit = function () {
    FB.init({
        appId: '@ConfigSettings.FacebookAppId',
        xfbml: true,
        version: 'v2.4'
    });
};

(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

I'm attempting to log a user out of facebook with the Facebook JS SDK, however calling:

FB.getLoginStatus(function facebookLogoutCallback(facebookResponse) {
    if (facebookResponse.status !== 'connected') {
        return;
    }

    FB.logout(facebookLogoutCallback);
});

leads to status unknown instead of connected, which is returned in facebookResponse object. I've also tried to call FB.logout() without if statement, but it didn't work.

Maybe you can say, that this behavior is caused by unauthorized user status, but after server side login the user is actually logged in: on my website and Facebook too.

解决方案

It seems that there's a bug currently in the FB.logout function. After calling it the user can not be logged into this App again using the JS SDK because the FB.login function returns
Object { status="unknown", authResponse=null}

EDIT:
Found that there's a cookie called "fblo_*" created after FB.logout() which seems to be the reason for this. I can't say exactly why it's there and what it does, but deleting it makes the login work again.

Therefor I created a small script that looks for this cookie and deletes it just before I call FB.login() which you probably want to call in a click event (https://developers.facebook.com/docs/reference/javascript/FB.login/v2.5).

function delete_cookie(name) 
{
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
}


var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
    if(cookies[i].split("=")[0].indexOf("fblo_") != -1)
        delete_cookie(cookies[i].split("=")[0]);
}

这篇关于当使用Facebook JS SDK从Facebook注销时,getLoginStatus返回状态未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆