在WebAPI2 OWIN中如何结合承载令牌和OAuth2?

时间:2016-09-19 15:14:37

标签: authentication oauth-2.0 asp.net-web-api2 owin

我是ASP.NET身份验证的新手,现在正在使用身份验证方法。我想为用户名/密码身份验证实施不记名令牌,我也希望外部用户通过Google和其他OAuth2提供商登录。

我无法同时实现这两种方法。我在这种富含选项的OWIN配置中做错了。

这是我的SecurityConfig类:

public class SecurityConfig
{
    public static void Configure(IAppBuilder app)
    {
        ConfigureTokenAuthentication(app);
        ConfigureExternalAuthentication(app);
    }

    private static void ConfigureTokenAuthentication(IAppBuilder app)
    {
        string PublicClientId = "self";
        Func<UserManager<User>> UserManagerFactory = () => new UserManager<User>(new UserStore<User>(new TicketsContext()));
        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = false
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);
    }

    private static void ConfigureExternalAuthentication(IAppBuilder app)
    {
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
            LoginPath = new PathString("/api/Account/ExternalLogin")
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure Google authentication
        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
        {
            ClientId = "my client id here",
            ClientSecret = "my client secret here"
        });         
    }
}

这是外部登录方法:

// GET api/Account/ExternalLogin
[HttpGet]
[AllowAnonymous]
[Route("api/Account/ExternalLogin")]
public IHttpActionResult ExternalLogin(string provider)
{
    return new ChallengeResult(provider, "/api/home", this.Request);
}

当我启用这两种方法时,只是承载令牌正常工作,尝试进行外部登录会回答我“error:invalid_request”并且不会进入控制器方法。

这行可能有问题吗?

AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),

已经尝试解决这个问题2天了。

1 个答案:

答案 0 :(得分:0)

UseGoogleAuthentication实施的OAuth2流程不适用于WebApi场景,它依赖于用户交互。承载令牌是WebApis的正确方法。要获得代表外部身份提供商(如Google)的承载令牌,请使用IdentityServer3等中间身份验证服务器。见https://github.com/IdentityServer/IdentityServer3