3

I am relatively new to the concept of middlewares. I am aware that a middleware calls the next middleware when it completes.

I am trying to authenticate a request using either Google or my Identity Server. The user can login on my mobile app with google or a local account. However, I can't figure out how to use both authentication middlewares. If I pass the id_token for google, it passes on the first middleware (UseJwtBearerAuthentication) but fails on the second one (UseIdentityServerAuthentication). How can I make it so that it doesn't throw error when it actually passes on at least 1 authentication middleware? For example, if it passes on the first middleware, the second middleware is ignored?

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    Authority = "https://accounts.google.com",
    Audience = "secret.apps.googleusercontent.com",
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateAudience = true,
        ValidIssuer = "accounts.google.com"
    },
    RequireHttpsMetadata = false
});

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:1000/",
    RequireHttpsMetadata = false,

    ScopeName = "MyApp.Api"
});
4

1 回答 1

6

通常,当一个身份验证中间件失败(我不是指抛出异常)时,这不会影响另一个成功的身份验证中间件。可能您的第二个中间件会引发异常(不是验证失败)。首先检查错误消息并尝试解决它。如果不能,请使用AuthenticationFailed事件来处理错误。在这种情况下,您的代码应如下所示:

 app.UseJwtBearerAuthentication(new JwtBearerOptions()
 {
     // ...
     Events = new JwtBearerEvents()
     {
          OnAuthenticationFailed = async (context) =>
          {
              if (context.Exception is your exception)
              {
                   context.SkipToNextMiddleware();
              }
          }
     }
 });

但是,对于您的场景,我不会选择您的方式。我只会使用身份服务器端点。要使用 google 签名,您可以配置身份服务器,如下所示:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
            AutomaticAuthenticate = false,
            AutomaticChallenge = false
        });

        app.UseGoogleAuthentication(new GoogleOptions
        {
            AuthenticationScheme = "Google",
            SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
            ClientId = "",
            ClientSecret = ""
        });

        app.UseIdentityServer();

编辑

似乎AuthenticationFailed事件不能用于IdentityServer4.AccessTokenValidation. 我不确定,但如果您将身份服务器仅用于 jwt 令牌,则可以UseJwtBearerAuthentication用于验证。

于 2016-09-20T04:36:47.287 回答