【问题标题】:The signature key was not found error when using IndentityServer4 with Angular, AspNet Core将 IdentityServer4 与 Angular、Asp Net Core 一起使用时找不到签名密钥错误
【发布时间】:2018-05-03 04:23:05
【问题描述】:

我的解决方案中有 3 个项目,其中一个是 Idp,使用 IdentityServer4 并具有以下配置。我正在使用Implicit Flow

    public void ConfigureServices(IServiceCollection services)
{
    var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");


    // Add framework services.
    var connectionString = Configuration.GetConnectionString("PostgreSQLConnectionString");
    Console.WriteLine(connectionString);
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(connectionString));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    //NB added for implicit flow
    services.AddCors();

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();


    services.AddIdentityServer()
        //.AddTemporarySigningCredential()
        .AddSigningCredential(cert)
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(IdentityServerStatics.GetIdentityResources())
        .AddInMemoryApiResources(IdentityServerStatics.GetApiResources())
        .AddClientStore<CustomClientStore>() // Add the custom client store
        .AddAspNetIdentity<ApplicationUser>()
        .AddProfileService<CustomProfileService>(); // use custom profile service to pull in claims

    services.AddAuthorization(options =>
    {
        options.AddPolicy("MyUMD_User", policy => policy.RequireClaim("MyUMD:AccessLevel", "User", "Manage", "Support", "Admin"));
    });
    services.AddAuthorization(options =>
    {
        options.AddPolicy("MyUMD_Manage", policy => policy.RequireClaim("MyUMD:AccessLevel", "Manage", "Support", "Admin"));
    });
    services.AddAuthorization(options =>
    {
        options.AddPolicy("MyUMD_Support", policy => policy.RequireClaim("MyUMD:AccessLevel", "Support", "Admin"));
    });
    services.AddAuthorization(options =>
    {
        options.AddPolicy("MyUMD_Admin", policy => policy.RequireClaim("MyUMD:AccessLevel", "Admin"));
    });
}

资源服务器配置如下。

注意此资源服务器已经在使用自定义 JWT 令牌生成和验证。现在我想添加额外的功能来从IdentityServer4生成的令牌中读取声明

public void ConfigureJwtAuthService(IServiceCollection services)
    {
        var folderForKeyStore = Configuration["Production:KeyStoreFolderWhichIsBacked"];
        var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");

        // Important The folderForKeyStore needs to be backed up.
        services.AddDataProtection()
            .SetApplicationName("vast_webapplication")
            .PersistKeysToFileSystem(new DirectoryInfo(_env.ContentRootPath))
            .ProtectKeysWithCertificate(cert);



        var symmetricKeyAsBase64 = "Y2F0Y2hlciUyMHdvbmclMjBsb3ZlJTIwLm5ldA==";
        var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
        var signingKey = new SymmetricSecurityKey(keyByteArray);

        // JWT Token signing settings
        TokenAuthOptions tokenAuth = new TokenAuthOptions()
        {
            Audience = "vast-audience",
            Issuer = "vast-issuer",
            // this gets set later in Configure
            SigningCredentials = null,
            Key = signingKey
        };

        // add the auth options to the DI container
        services.AddSingleton(tokenAuth);

        var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = "vast-issuer",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = "vast-audience",

            // Validate the token expiry
            ValidateLifetime = true,

            ClockSkew = TimeSpan.FromMinutes(60)
        };

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(o =>
        {
           o.TokenValidationParameters = tokenValidationParameters;
        });
        //.AddCookie(options=> options.Cookie.Domain="localhost:5000");


        services.AddAuthorization(options => {
            //options.DefaultPolicy= new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();

            options.AddPolicy(AuthorizationPolicies.TicketTypeRead, policy => {
                policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                policy.RequireClaim(CustomClaims.TicketTypRead);
            });


            string[] roles = new string[] { "User", "Management" };
            options.AddPolicy("Reporting_Managers", policy =>
            {
                policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                policy.RequireClaim("SkyBusReporting:Reporting", "Management");
            });

        });
    }

Angular 应用程序也是一个 .net 项目,它成功调用了 api(资源服务器功能)。作为回应,我收到了 401 Unauthorized 状态,在标题中我可以看到这个

www-authenticate →Bearer error="invalid_token", error_description="The 未找到签名密钥”

我在这里做错了什么?

【问题讨论】:

  • 我没有看到您将 API/资源服务器指向 IndentityServer4 实现的位置。
  • 我不需要。我的 Angular 应用程序指向 idp,并且在主页加载 Angular 应用程序将页面重定向到 idp 登录页面。登录后 idp 使用不记名令牌重定向回 Angular 主页。我只需要在资源 api 中配置 jwt 令牌读取器即可读取声明。
  • 你能澄清一下在资源 API 中使用 IdentityServer4 是什么意思吗?
  • 是的你写我不需要资源 api 中的 idp 我只需要公钥来读取资源 api 中的令牌
  • 所以你想调用一个不是 IdentityServer4 客户端的 api 并从承载令牌中读取声明,对吗?

标签: angular identityserver4 asp.net-core-2.0


【解决方案1】:

感谢aaronR 我在我的代码中发现了问题。现在我不确定这是否是实现implicit flow的最佳方式

我更改了我的代码是资源 api 以使用证书中的公钥来读取上面代码中缺少的令牌。

在上面的 ConfigureJwtAuthService 函数中,我更改了代码以从证书中获取密钥,如下所示

var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "damienbodserver.pfx"), "");
        X509SecurityKey key = new X509SecurityKey(cert);
        SigningCredentials credentials = new SigningCredentials(key, "RS256");

比我在TokenValidationParameters 对象中使用这个键如下

var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            //IssuerSigningKey = signingKey,
            IssuerSigningKey = key,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = false,
            ValidIssuer = "vast-issuer",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = false,
            ValidAudience = "vast-audience",

            // Validate the token expiry
            ValidateLifetime = true,

            ClockSkew = TimeSpan.FromMinutes(60)
        };

我还更改了自定义 JWT 令牌生成的实现,以使用相同的密钥和凭据来生成 JWT 令牌。

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 2018-12-20
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2022-07-13
    • 2020-02-22
    相关资源
    最近更新 更多