首页 文章

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

提问于
浏览
7

我正在尝试使用外部承载令牌实现Facebook登录 . 我在VS 2013中创建了新项目,并选择了个人用户帐户身份验证,就像在这个tulorial http://www.asp.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结果 .

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

1 回答

  • 1

    我还没有找到解决这个问题的方法 . 但我以另一种方式解决了任务 . 我添加了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;
        }
    }
    

相关问题