Wep-Api在Facebook身份验证后登录

本文关键字:登录 身份验证 Facebook Wep-Api | 更新日期: 2023-09-27 18:00:50

我发布的这个问题措辞不当,没有得到回应。所以我想我应该简化我的问题。

在我的webapi中,我需要在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);

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

Wep-Api在Facebook身份验证后登录

得到了一个有效的解决方案。首先,我需要在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;
}

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