PacktPublishing / Keycloak---Identity-and-Access-Management-for-Modern-Applications-2nd-Edition

Keycloak - Identity and Access Management for Modern Applications, 2nd Edition
MIT License
98 stars 34 forks source link

CH02 - Invoke Service return 403 but myrole is added to access_token #19

Open jockexa opened 1 year ago

jockexa commented 1 year ago

I have a bit of a strange issue where "myrole" is added to the access_token but Invoke Service function still return "403 - Access Denied"

"Show Access Token" image

Text after pressing "Invoke Service" button at http://localhost:8000/ image

fluke777 commented 11 months ago

Seeing the same issues. Did you manage to resolve it?

fluke777 commented 11 months ago

Staring for a bit into the source code of keycloak-node-connect I think I figured out the issue in my case. Since it was something I created it might not be the same in your case but maybe it helps someone else.

The issue was I changed this line

app.get("/secured", keycloak.protect("realm:myrole"), function (req, res) {

to this

app.get("/secured",` keycloak.protect("myrealm:myrole"), function (req, res) {

Since I thought the realm has to be the name of the realm. But it is a description where the role should be looked for. The algorithm of the keycloak protector is here and the check for the role Token.prototype.hasRole that is uses is here.

Here is the working function with couple of printouts that might help you debug.

app.get("/secured", keycloak.protect("realm:myrole"), function (req, res) {
  let tok = req.kauth.grant.access_token;

  console.log(tok.hasRole("realm:myrole"));

  res.setHeader("content-type", "text/plain");
  res.send("Secret message!");
});
bjorntj commented 9 months ago

I am having the same issue, any solutions?

borisekm commented 8 months ago

For me the problem was that in docker it wasn't working but running npm start directly was OK.

0xamrzaky commented 4 months ago

https://github.com/PacktPublishing/Keycloak-Identity-and-Access-Management-for-Modern-Applications/issues/27#issuecomment-1822036222