1
votes

I secured my NODE.js App with keycloak and it works fine

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. Is there a chance to read the roles of the current user?

4

4 Answers

6
votes

the loadUserInfo does not provide the roles of the user you may use the keycloak-js and get the roles by 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

2
votes

Currently, parsing the tokenParsed object does not contain the exact role information user has. It does have the resource_access object and inside we can check for the client we are interested in and then the roles. 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.

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.

Then, go to client and in the Mapper tab, add new mapper with type User Attribute.

This gives you your desired attribute (i.e. prime_role) in return when you parse above tokenParsed object.

Hope this helps.

2
votes

As of Keycloak-js 11.0.2 (at least) you can directly access array of roles, without parsing the token, by

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

Do this:

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

Then you can see in the console: Console Image