Wep Api Facebook 验证后登录

Wep Api Sign In After Facebook Authentication

我发布的 this question 措辞不当,没有产生回复。所以我想我应该简化我的问题。

在我的网站 api 中,我需要在 Facebook 告诉我他们已通过身份验证后让用户登录我的应用程序。如果我有自己的 OAuth 服务器,我会这样做:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = new AuthorizationServerProvider(container.Resolve<IAuthenticationRepository>())
};

app.UseOAuthAuthorizationServer(OAuthServerOptions);

允许用户登录我的 /token 端点。我不想公开 /token 端点,因为我只使用外部登录,但我需要连接到我的 OAuthServerProvider。在 facebook 对它们进行身份验证后,我想从服务器端生成一个令牌。如何连接到我自己的 OAuthServerProvider 以获得令牌?

找到了可行的解决方案。首先,我需要在 Startup:

中将 BearerAuthentication 添加到我的应用程序中
public class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

    public void Configuration(IAppBuilder app)
    {
       //other code

       OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions();
       app.UseOAuthAuthorizationServer(OAuthServerOptions); 

       OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
       app.UseOAuthBearerAuthentication(OAuthBearerOptions);

       //other code
    }

就像我说的,我不希望端点可用于为客户端获取令牌,因为当用户通过 facebook 进行身份验证时,我是唯一一个请求令牌的人。所以我的 OAuthServerOptions 没有声明 TokenEndpoint

的值

然后,当我使用 facebook 验证用户身份并准备向他们颁发令牌时,我使用 OAuthBearerOptionsAuthenticationTicket:

生成令牌
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

这是使用令牌生成响应的完整方法(摘自很棒的博客 BitOfTech

private JObject GenerateLocalAccessTokenResponse(string userName)
{
    var tokenExpiration = TimeSpan.FromDays(1);

    ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);

    identity.AddClaim(new Claim(ClaimTypes.Name, userName));
    identity.AddClaim(new Claim("role", "user"));

    var props = new AuthenticationProperties()
    {
        IssuedUtc = DateTime.UtcNow,
        ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
    };

    var ticket = new AuthenticationTicket(identity, props);
    var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);

    JObject tokenResponse = new JObject(
                            new JProperty("userName", userName),
                            new JProperty("access_token", accessToken),
                            new JProperty("token_type", "bearer"),
                            new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                            new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                            new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
                            );

     return tokenResponse;
}

现在我有一个令牌可供客户端使用。