从Java API访问keycloak角色/用户属性 [英] Accessing keycloak roles / users attributes from Java API
问题描述
我已经在Keycloak中创建了一个角色和一个用户,并在两个角色中都添加了一个属性;例如:
I've created a role and and a user in Keycloak and added one attribute in both of them; for example:
my_role_attr = 'x'
my_user_attr = 'y'
然后我正在尝试访问该信息.通过JAVA KeycloakSecurityContext(以及关联的AccessToken/IDToken).我可以看到角色的名称和用户信息,但是找不到这些属性.
Then I'm trying to access that info. via the JAVA KeycloakSecurityContext (and the associated AccessToken / IDToken). I can see the name of the roles and the user information but I cannot find those attributes.
我了解我必须创建一个协议映射器用户属性",以将"my_user_attr"映射到令牌声明中.没关系,我可以在AccessToken/IDToken中获取值.
I understand that I've to creat a Protocol Mapper "User Attribute" to map the "my_user_attr" into a Token Claim. Then it's fine I can get the value in the AccessToken / IDToken.
但是我找不到获取角色属性的方法.我没有看到任何"Protocol Mapper"作为角色属性.我想念什么吗?
But I cannot find a way to get the role attribute. I do not see any "Protocol Mapper" for role attribute. Am I missing something.
推荐答案
我一直在尝试做同样的事情;这并不容易,但是您可以成功使用脚本映射器.源代码位于如何创建
I have been trying to do the same thing; and it is not easy, however you can use the script mapper with some success. The source code at https://github.com/keycloak/keycloak/blob/master/server-spi/src/main/java/org/keycloak/models/RoleModel.java has some useful information. This SO item (thank you Andre B) also has useful information How to create a Script Mapper in Keycloak?.
我的解决方案(不是完美的或不完整的)是:
My (not perfect or complete) solution is:
/**
* Available variables:
* user - the current user
* realm - the current realm
* token - the current token
* userSession - the current userSession
* keycloakSession - the current userSession
*/
var roles = [];
var client = keycloakSession.getContext().getClient();
user.getClientRoleMappings(client).forEach(function(roleModel) {
var attr = [];
var names = {};
var rn = roleModel.getName();
var map = roleModel.getAttributes();
map.forEach(function(key, value){
var k = {};
var a = false;
value.forEach(function(l){
a = (l === 'true');
});
k[key] = a;
attr.push(k);
});
names[rn] = attr;
roles.push(names);
});
exports = roles;
请注意,您可能需要将多值"设置为"ON",并将声明JSON类型"设置为选择一个..".
Note that you probably need to set 'Multivalued' to "ON" and the 'Claim JSON Type' to "Select One..".
这篇关于从Java API访问keycloak角色/用户属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!