2013-12-17 53 views
7

我試圖實現Facebook登錄使用外部承載令牌。我在VS 2013中創建了一個新項目,並選擇了個人用戶帳戶認證,如在這個調查http://www.asp.net/web-api/overview/security/external-authentication-services中。Facebook登錄使用外部承載令牌(MVC4 Web Api)

我配置了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)的作品。

我調用GET請求小提琴手:

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

但我收到401結果。

我必須通過外部承載令牌進行身份驗證嗎?

+0

你在哪裏得到來自Facebook的令牌? –

+0

@Neshta你在這裏找到了解決方案嗎? – Syska

+0

這裏同樣的問題。我有一個Facebook標記,但無法訪問標有外部承載的WebAPI方法。 – creatiive

回答

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