4

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

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
  • 1
    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 – Evil_skunk Jun 14 '20 at 07:01

4 Answers4

2

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

Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
1

In you KeyCloack configuration variable, you can use credentials and not realmPublicKey.

0

I got the same problem. Also used the example code from here

The only adjustment to the example code is creating the session. here there was always an error message with the example code.

My code:

index.js:

// index.js
var express = require('express');
var app = express();
const cors = require('cors');

app.use(cors());

const session = require('express-session');
const memoryStore = new session.MemoryStore();
app.use(session({
  secret: 'some secret',
  resave: false,
  saveUninitialized: true,
  store: memoryStore
}));

const keycloak = require('./config/keycloak-config.js').initKeycloak(memoryStore);
app.use(keycloak.middleware({
  logout: '/logout',
  admin: '/'
}));

const testController = require('./controller/test-controller.js');
app.use('/test', testController);

app.get('/', function (req, res) {
  res.send("Server is up!");
});

app.listen(3000);

keycloak-config.js:

// keycloak-config.js
var session = require('express-session');
var Keycloak = require('keycloak-connect');

let _keycloak;

var keycloakConfig = {
    clientId: 'test-client',
    bearerOnly: true,
    serverUrl: 'http://localhost:8080/auth',
    realm: 'test',
    credentials: {
        secret: 'xS9K7RpUah5PzWQZh6BaAGX8Ochr6RY6'
    }
};

function initKeycloak(memoryStore) {
    if (_keycloak) {
        console.warn("Trying to init Keycloak again!");
        return _keycloak;
    } 
    else {
        console.log("Initializing Keycloak...");
        _keycloak = new Keycloak({ 
          store: memoryStore
        }
        , keycloakConfig
        );
        return _keycloak;
    }
}

function getKeycloak() {
    if (!_keycloak){
        console.error('Keycloak has not been initialized. Please called init first.');
    } 
    return _keycloak;
}

module.exports = {
    initKeycloak,
    getKeycloak
};

test-controller.js:

// test-controller.js
var express = require('express');
var router = express.Router();
const keycloak = require('../config/keycloak-config.js').getKeycloak();

router.get('/anonymous', function(req, res){
    res.send("Hello Anonymous");
});

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

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

router.get('/all-user', keycloak.protect(['user','admin']), function(req, res){
    res.send("Hello All User");
});

module.exports = router;
Shades
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 04 '22 at 06:10
0

Change the bearerOnly option to false

var keycloakConfig = {
  clientId: "nodejs-microservice",
  bearerOnly: false,
  serverUrl: "http://localhost:8083/auth",
  realm: "Demo-Realm",
  credentials: {
    secret: "8ZkObGg73gr26TtAPE9TKVC7QmQikNMx",
  },
};
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
120m4n
  • 21
  • 5