IdentityServer4 令牌签名验证

IdentityServer4 token signing validation

我有生成签名 JWT 令牌的 IdentityServer4。 在我的网站 api 中,我添加了 auth 中间件来验证这些令牌:

         app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            Authority = env.IsProduction() ? "https://www.example.com/api/" : "http://localhost/api/",
            AllowedScopes = { "WebAPI", "firm",
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile },
            RequireHttpsMetadata = env.IsProduction(),
        });

效果很好。但是,我怀疑它不会验证 jwt 令牌的签名,因为没有配置 public 密钥来验证令牌。如何配置令牌签名验证?

PS:我尝试以这种方式使用 UseJwtBearerAuthentication:

        var cert = new X509Certificate2("X509.pfx", "mypassword");
        var TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidIssuer = env.IsProduction() ? "https://www.example.com/api/" : "http://localhost/api/",
            IssuerSigningKey = new X509SecurityKey(cert),
        };
        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            Authority = env.IsProduction() ? "https://www.wigwam3d.com/api/" : "http://localhost/api/",
            Audience = "WebAPI",
            RequireHttpsMetadata = env.IsProduction(),
            TokenValidationParameters = TokenValidationParameters
        });

它也有效(我希望也能验证令牌签名!)但又给我带来了另一个错误:

UserManager.GetUserAsync(HttpContext.HttpContext.User)

return null,使用 UseIdentityServerAuthentication return 是我正确的用户

最后我用 JwtBearerAuthentication 完成了,

GetUserAsync 函数失败可以通过调用来修复:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

因为这个问题:https://github.com/aspnet/Security/issues/1043

欢迎使用 IdentityServer 身份验证配置相同的任何想法!

我认为没有必要给你添加证书API来验证。 .UseIdentityServerAuthentication() 中间件调用您的 IdentiyServer 以在启动时从 https://www.example.com/api/.well-known/openid-configuration 检索 public 密钥。至少我是这样理解它是如何工作的。