将工作 IdentityServer4 解决方案从 v3 迁移到 v4 后,如何修复 MVC 应用和 API 上的运行时错误?
IdentityServer4 设置:
var builder = services.AddIdentityServer(
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddTestUsers(TestUsers.Users);
public static IEnumerable<ApiResource> Apis =>
new ApiResource[]
{
new ApiResource("api1"),
new ApiResource("api2")
};
MVC 客户端配置:
new Client
{
ClientName = "MVC website",
ClientId = "mvcclient",
ClientSecrets =
{
new Secret("secret2".Sha256())
},
AllowedGrantTypes = GrantTypes.Code,
RequireConsent = false,
RequirePkce = true,
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes = {"openid", "profile", "offline_access", "api1", "api2" },
AllowOfflineAccess = true,
},
MVC 应用 OpenId Connect 设置:
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvcclient";
options.ClientSecret = "secret2";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("api1");
options.Scope.Add("api2");
options.Scope.Add("offline_access");
options.GetClaimsFromUserInfoEndpoint = true;
});
迁移后出错:
Sorry, there was an error : invalid_scope
Invalid scope
API 设置:
services.AddAuthentication("Bearer").AddJwtBearer("Bearer",
options =>
{
options.Authority = "http://localhost:5000";
options.Audience = "api1";
options.RequireHttpsMetadata = false;
});
迁移后 API 错误:
401 Unauthorized
最佳答案
简短的答案是遵循migration-steps-to-v4
As described above, starting with v4, scopes have their own definition and can optionally be referenced by resources. Before v4, scopes where always contained within a resource.
To migrate to v4 you need to split up scope and resource registration, typically by first registering all your scopes (e.g. using the AddInMemoryApiScopes method), and then register the API resources (if any) afterwards. The API resources will then reference the prior registered scopes by name.
我已将其写在博客上 https://nahidfa.com/posts/migrating-identityserver4-to-v4/经历这些变化及其背后的推理。
关于migration - 将 IdentityServer4 从 v3 迁移到 v4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722368/