【问题标题】:In WebAPI2 OWIN how to combine bearer tokens and OAuth2?在 WebAPI2 OWIN 中如何结合不记名令牌和 OAuth2?
【发布时间】:2017-01-27 08:17:33
【问题描述】:

我是 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);
}

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

这行可能有问题?

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

已经尝试解决此问题 2 天。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2014-01-04
      • 2013-04-10
      • 1970-01-01
      • 2018-06-01
      • 2014-01-05
      • 1970-01-01
      相关资源
      最近更新 更多