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?
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
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.