【发布时间】:2018-03-14 20:12:08
【问题描述】:
在我的客户端中,我进行了以下设置。
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
//options.DefaultSignInScheme = "Cookies",
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "...";
options.ClientId = "...";
options.SaveTokens = true;
options.ClientSecret = "secret";
options.SignInScheme = "Cookies";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("roles");
options.ResponseType = "code id_token";
options.GetClaimsFromUserInfoEndpoint = true;
options.Events = new OpenIdConnectEvents()
{
OnTokenValidated = tokenValidatedContext =>
{
var identity = tokenValidatedContext.Principal.Identity
as ClaimsIdentity;
var targetClaims = identity.Claims.Where(z =>
new[] {"sub"}.Contains(z.Type));
var newClaimsIdentity = new ClaimsIdentity(
targetClaims,
identity.AuthenticationType,
"given_name",
"role");
tokenValidatedContext.Principal =
new ClaimsPrincipal(newClaimsIdentity);
return Task.CompletedTask;
},
OnUserInformationReceived = userInformationReceivedContext =>
{
return Task.FromResult(0);
}
};
});
我在 IdentityServer 级别的客户端定义如下。
new Client()
{
ClientName = "My App",
ClientId = "mymagicapp",
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>()
{
"https://..."
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"roles"
},
ClientSecrets = { new Secret("secret".Sha256()) },
PostLogoutRedirectUris =
{
"https://..."
}
}
新的“角色”范围如下添加。
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>()
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource("roles", "Your role(s)", new List<string>(){"role"})
};
}
用户定义如下。
new TestUser()
{
SubjectId = "abcdef",
Username = "Jane",
Password = "password",
Claims = new List<Claim>()
{
new Claim("given_name", "Jane"),
new Claim("family_name", "Doe"),
new Claim("role", "FreeUser")
}
}
登录到我的 MVC 客户端后,在 Controller 中,User.Claims 对象不包含 role 声明。
但是,在 OnUserInformationReceived 中,userInformationReceivedContext 的 User 对象确实包含 role 声明。
我错过了什么?
【问题讨论】:
-
我有一个建议 - 在第一次测试中尝试使用另一个声明名称。角色声明是 OpenId 的一部分。只是为了确保没有重复,从其他东西开始,直到你弄明白,然后再改回你需要的东西。
-
感谢您的建议。我将
role(和rolesIdentityResource)重命名为其他名称,但它仍然没有出现在User.Claims上。用户声明似乎由于某种原因没有得到处理。 -
哦,我想我明白了 - 在 IdentityServer 级别的客户端中,将
AlwaysIncludeUserClaimsInIdToken设置为 true(默认为 false) -
是的,这可能会解决问题,但会增加 cookie 的大小。这是我要避免的。
标签: asp.net-core-2.0 identityserver4