我的解决方案中有3个项目,其中一个是使用IdentityServer4
的 Idp,配置如下。我正在使用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未经授权的状态,在标头中我可以看到这个:
www-authenticate →Bearer error="invalid_token", error_description="The signature key was not found"
在这里我做错了什么?