asp.net - 多个身份验证中间件 ASP.NET Core

标签 asp.net asp.net-core identityserver4

我对中间件的概念还比较陌生。我知道中间件在完成时会调用下一个中间件。

我正在尝试使用 Google 或我的身份服务器对请求进行身份验证。用户可以使用谷歌或本地帐户登录我的移动应用程序。但是,我不知道如何使用这两个身份验证中间件。如果我传递 google 的 id_token,它会传递第一个中间件 (UseJwtBearerAuthentication),但在第二个中间件 (UseIdentityServerAuthentication) 上失败。我怎样才能使它在实际传递至少 1 个身份验证中间件时不会抛出错误?比如传递第一个中间件,第二个中间件就被忽略?

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"
});

最佳答案

通常,当身份验证中间件失败时(我不是指抛出异常),这不会影响另一个成功的身份验证中间件。您的第二个中间件可能会引发异常(不是验证失败)。首先检查错误消息并尝试解决它。如果不能,请使用 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 token ,则可以使用 UseJwtBearerAuthentication 进行验证。

关于asp.net - 多个身份验证中间件 ASP.NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39580825/

相关文章:

c# - 如何将 RoutePattern 添加到 Endpoint 对象

Azure key 保管库证书 : the key was not found

c# - asp.net 5/vnext 磁盘上没有 dll 的代码契约(Contract)

IdentityServer4 - 注销后重定向到 MVC 客户端

asp.net-core - 带有 IdentityServer4 的 appsettings.json 中的 ClientSecret

docker - LetsEncrypt 的 TLS 证书是否应该位于所有容器上?

asp.net - oauth 身份验证后获取 Twitter 用户名

asp.net - 以编程方式检索 ASP.NET 应用程序中的 IIS 日志文件位置

.net - 我需要在 ASP.NET 中使用 AJAX 关心线程安全吗?

asp.net - 如何查找基本 Azure 网站的计算机名称