简体   繁体   English

在 Keycloak 中获取登录用户的角色

[英]Get Roles of logged-in User in Keycloak

I secured my NODE.js App with keycloak and it works fine我用 keycloak 保护了我的 NODE.js 应用程序,它工作正常

var Keycloak = require('keycloak-connect');
var session = require('express-session');
var keycloak = null;
var memoryStore = new session.MemoryStore();
keycloak = new Keycloak({
    store: memoryStore
});

app.get('/portal', keycloak.protect(), function (req, res) {
    res.sendFile(path.join(__dirname, '/views/index.html'));
});

in the portal (index.html) I have to show / hide different parts of the page according to the user's role in keycloak.在门户 (index.html) 中,我必须根据用户在 keycloak 中的角色来显示/隐藏页面的不同部分。 Is there a chance to read the roles of the current user?是否有机会读取当前用户的角色?

the loadUserInfo does not provide the roles of the user you may use the keycloak-js and get the roles by tokenParsed loadUserInfo不提供用户的角色,您可以使用 keycloak-js 并通过tokenParsed获取角色

var Keycloak = require('keycloak-js');
var kc = Keycloak('./keycloak.json');

kc.init().success(function(authenticated) {

   alert(JSON.stringify(kc.tokenParsed)); 

}).error(function() {
            alert('failed to initialize');
});

Hope it helps希望它有帮助

Currently, parsing the tokenParsed object does not contain the exact role information user has.目前,解析tokenParsed对象不包含用户拥有的确切角色信息。 It does have the resource_access object and inside we can check for the client we are interested in and then the roles.它确实有resource_access对象,在里面我们可以检查我们感兴趣的客户端,然后是角色。 But this may also contains multiple roles assigned for that client.但这也可能包含为该客户端分配的多个角色。

In such a scenario, the best way is to take advantage of keycloaks user Attribute feature.在这种情况下,最好的方法是利用 keycloaks 用户Attribute功能。

Simply set an attribute on user level in the attribute tab, such as prime_role and value to the role you primarily want to assign to this user.只需在属性选项卡中设置用户级别的属性,例如prime_role和您主要希望分配给该用户的角色的值。

Then, go to client and in the Mapper tab, add new mapper with type User Attribute .然后,转到客户端并在Mapper选项卡中,添加类型为User Attribute新映射器。

This gives you your desired attribute (ie prime_role ) in return when you parse above tokenParsed object.当您解析上面的tokenParsed对象时,这将为您提供所需的属性(即prime_role )作为回报。

Hope this helps.希望这会有所帮助。

As of Keycloak-js 11.0.2 (at least) you can directly access array of roles, without parsing the token, by从 Keycloak-js 11.0.2(至少)开始,您可以通过以下方式直接访问角色数组,而无需解析令牌

constructor(public keycloakService: KeycloakService) { }
console.log(this.keycloakService.getKeycloakInstance().realmAccess.roles);

Do this:这样做:

constructor(public keycloakService: KeycloakService) { }
console.log(this.keycloakService.getKeycloakInstance().tokenParsed['roles']);

Then you can see in the console: Console Image然后就可以在控制台中看到: Console Image

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM