Search code examples
node.jskeycloakkeycloak-connectkeycloak-nodejs-connect

NodeJs and Keycloak Integration giving 403?


I just took the demo code from this Github So i change the keycloak-config.json

 var keycloakConfig ={
        clientId: 'my-api',
        bearerOnly: true,
        serverUrl: 'https://<IPADDRESS>:8443/auth/',
        realm: 'myrealm',
        credentials: {
            secret: '99e71ca7-f25b-40b5-87ed-0af2656b52ac'
        }
    };

Now to access the api endpoint first i will generate the token enter image description here

With the help of above token i am trying to access secure API enter image description here

But it will fail with the error

403: Access Denied

Here is code

router.get('/user', keycloak.protect(), function(req, res){
    res.send("Hello User");
});

Even this also giving same

router.get('/user', keycloak.protect('user'), function(req, res){
    res.send("Hello User");
});

I followed this link for this demo code


Solution

  • After i found the solution i saw the comment as well ,my solution and comment matched so we have to make following changes,in place of credentials we have to use realmPublicKey

    var keycloakConfig ={
        clientId: 'my-api',
        bearerOnly: 'true',
        serverUrl: 'https://<IPADDRESS>:8443/auth/',
        realm: 'myrealm',
        sslRequired: 'external',
        realmPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhGpeNPTzIA0SpqWtOU27C3lCdHkLzWiYc3voiBZvvZdvk4wW96JymHlX2b0weDnkYfurxIRehRA0sLK8w2vjb3X9TdKOcsiQzHlWDQuA3Wu7WeDGcvv8dyDk+bMOSkqn7bMlOUm6CXxA7RrjKuDj8mseqabXNjnPgAPL6MQOWtO4RFMdPQX11fYShXrK9ELS3CqN3RrXBazzwNsreKxfuMtR4vtZCVJHYaZZMiLmWU1G5Xsh/tHje2AVLPkt3ncchyKsrkCdP9PWsYK5dMkKsDbA03JOq7azDDlhqgT2pUNB3dZ1b9sKQXqPC6ZSieVJcm6WAj8DJcjoYOgZjgm2/8X1fwIDAQAB',
    
    };
    

    Just adding what @Evil_skunk written

    do you get some additional errors on the nodejs side? otherwise I can just do some wild guessing ;-) you are accessing keycloak over https, is the used cert trusted by nodejs? if you send an access_token to nodejs, this token need to be validated with the realms public key. this key is normally fetched from a kc-ednpoint, maybe this isn't possible in your case