The route look like this where verifytoken is a middleware.
router.get('/v1/endpoint', verifytoken, apis.getData);
In order to protect this route we will generally use keycloak.protect(); but I want to use verifytoken which is a middleware and always go to apis.getDatat irrespective of whether the route is protected or not. But the middleware function will attach a string based on if the user is authenticated or not.
router.get('/v1/endpoint', keycloak.protect(), apis.getData);
This code should run and protect the route and based on if it's authorized or not I want to add verified string that will be used by apis.getData to send the correct amount of data.
const keycloak = require('../../keycloak').getKeycloak();
/**
* @param {Object} request - request object with authorization header.
* @param {Object} response - response object.
* @param {Object} next - calls the next function with user payload.
*/
module.exports = function(request, response, next) {
// authorization token.
const token = request.headers.authorization;
// if token is not sent the authorization fails.
if (!token) {
return response.status(401).send('Access Denied, missing authorization token!');
}
// check if the token is valid or not.
try {
const verified = {};
if (keycloak.protect()) {
verified.verified = 'verified';
}
console.log('Token is verified', verified);
response.locals.user = verified;
next();
} catch (err) {
console.log('Token invalid!!!');
response.locals.user = 'unknown';
next();
}
};
Code for configuring keycloak
const session = require('express-session');
const Keycloak = require('keycloak-connect');
const keycloakConfig = require('./keycloak.json');
let _keycloak;
function initKeycloak() {
if (_keycloak) {
console.warn('Trying to init Keycloak again!');
return _keycloak;
}
console.log('Initializing Keycloak...');
const memoryStore = new session.MemoryStore();
_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,
};