首页 文章

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

提问于
浏览
0

我是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

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

相关问题