请告诉我为什么我不能向 OpenIdConnectOptions
添加任何范围?它不适用于 ASP.NET Core MVC 客户端,但与 js 客户端一起工作正常!
我的代码...
IdentityServer4客户端注册
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "web",
ClientName = "Web Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AlwaysIncludeUserClaimsInIdToken = true,
RedirectUris = {"http://localhost:5002/signin-oidc"},
PostLogoutRedirectUris = {"http://localhost:5002/signout-callback-oidc"},
AllowedCorsOrigins = {"http://localhost:5002"},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AccessTokenLifetime = 300,
IdentityTokenLifetime = 3600,
AllowOfflineAccess = true,
}
};
}
接下来,我将代码添加到 mvc 客户端以使用授权。
Mvc 客户端
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthorization(options =>
options.AddPolicy("AdminsOnly", policyUser =>
{ policyUser.RequireClaim("role", "admin"); }));
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
options.ClientId = "web";
options.SaveTokens = true;
});
当我尝试切换到标记有 [authorize]
属性的操作时,出现错误
Sorry, there was an error : invalid_scope.
如果我删除 options.Scope.Add("api 1");
行,则身份验证有效。但在这种情况下,我无法指定角色等等......
工程可以下载here
最佳答案
将此行添加到您的 MVC 客户端的 AddOpenIdConnect 选项以请求身份 token 和访问 token :
options.ResponseType = "id_token token";
您的 JS 客户端请求身份 token 和访问 token ,而 MVC 客户端仅请求身份 token 和资源身份 token 中不允许范围。参见 http://docs.identityserver.io/en/release/endpoints/authorize.html :
id_token requests an identity token (only identity scopes are allowed)
token requests an access token (only resource scopes are allowed)
关于c# - 具有范围的 Asp.net 核心 2.1 OpenIdConnectOptions 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52033154/