gpt4 book ai didi

angular - 将 IndentityServer4 与 Angular、AspNet Core 一起使用时,未找到签名 key 错误

转载 作者:行者123 更新时间:2023-12-02 10:51:59 25 4
gpt4 key购买 nike

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

    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 token 生成和验证。现在我想添加额外的功能来从 IdentityServer4 生成的 token 中读取声明

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 未经授权状态,在标题中我可以看到这一点

www-authenticate →Bearer error="invalid_token", error_description="The signature key was not found"

我在这里做错了什么?

最佳答案

感谢 aaronR 我在我的代码中找出了这个问题。现在我不确定这是否是实现隐式流程

的最佳方式

我更改了资源 api 的代码,以使用证书中的公钥来读取上述代码中缺少的 token 。

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

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

我在 TokenValidationParameters 对象中使用了这个 key ,如下所示

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 token 生成的实现,以使用相同的 key 和凭据来生成 JWT token 。

关于angular - 将 IndentityServer4 与 Angular、AspNet Core 一起使用时,未找到签名 key 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47383721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com