繁体   English   中英

Facebook使用外部承载令牌登录(MVC4 Web Api)

[英]Facebook login using external bearer token (MVC4 Web Api)

我正在尝试使用外部承载令牌实现Facebook登录。 我在VS 2013中创建了新项目,并选择了个人用户帐户身份验证,例如http://www.alyp.net/web-api/overview/security/external-authentication-services

我配置了facebook身份验证:

app.UseFacebookAuthentication(
            appId: "123[...]",
            appSecret: "123[...]");

一切正常。

我的测试方法:

[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("ExternalLogin2", Name = "ExternalLogin2")]
public async Task<IHttpActionResult> GetExternalLogin2()
{
    ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
    return Ok();
}

我不明白[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]的工作原理。

我在fiddler中调用GET请求:

GET http://localhost:17353/api/Account/ExternalLogin2 HTTP/1.1
Authorization: Bearer [my facebook token]
Content-Length: 28
Host: localhost:17353

但我收到401结果。

我必须做什么才能通过外部承载令牌进行身份验证?

我还没有找到解决这个问题的方法。 但我以另一种方式解决了任务。 我添加了HTTP标头X-Facebook-Token并将其传递给那里。 在覆盖方法OAuthAuthorizationServerProvider的GrantResourceOwnerCredentials(context)中,我从context.Request.Headers [“X-Facebook-Token”]中捕获了令牌。

string facebookToken = context.Request.Headers["X-Facebook-Token"];
if (facebookToken == null)
{
    context.SetError("invalid_grant", "Facebook token was not found in X-Facebook-Token header.");
    return;
}

dynamic facebookUser;
if (!FacebookUtil.TryGetUser(facebookToken, out facebookUser))
{
    context.SetError("invalid_grant", "Facebook token is incorrect.");
    return;
}

在FacebookUtil.TryGetUser()中我使用了Facebook库http://www.nuget.org/packages/facebook

public static bool TryGetUser(string facebookToken, out dynamic user)
{
    var facebookClient = new FacebookClient(facebookToken)
    {
        AppId = AppSettings.FacebookAppId,
        AppSecret = AppSettings.FacebookAppSecret
    };

    try
    {
        user = facebookClient.Get("me");
        return true;
    }
    catch (Exception)
    {
        user = null;
        return false;
    }
}

暂无
暂无

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

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