DEV Community

Cover image for Keycloak and Express
Austin Cunningham
Austin Cunningham

Posted on • Edited on

Keycloak and Express

This is a guide for setting up Express and Keycloak to protect web routes. Background Keycloak is an open source identity and access management solution that makes it easy to secure applications or microservices with little to no code. Express is a minimal and flexible Node.js web application framework. It can take a while to work your way through the official Keycloak documentation as the documentation is extensive and covers may different use cases .This a quick how to guide with minimum setup.

The goal is to create an Express app that uses Keycloak to protect the ‘/test ‘ route. The login and user setup are controlled by keycloak. The default route ‘/ ‘ is unprotected. The ‘/logout’ route kills the keycloak session.

To install keycloak-connect npm in your express application use the following command



npm install keycloak-connect --save


Enter fullscreen mode Exit fullscreen mode

Setup the Express server

You need to import keycloak-connect and express-sessions into your express application.



const Keycloak = require('keycloak-connect');
const session = require('express-session');


Enter fullscreen mode Exit fullscreen mode

Next configure the session to use memoryStore. Setup keycloak middleware to use the session memoryStore.



var memoryStore = new session.MemoryStore();                       
var keycloak = new Keycloak({ store: memoryStore });
//session                       
app.use(session({
    secret:'BeALongSecret',                         
    resave: false,                         
    saveUninitialized: true,                         
    store: memoryStore                       
}));

app.use(keycloak.middleware());


Enter fullscreen mode Exit fullscreen mode

You can then use keycloak.protect on your protected routes . This will check to see if a user is logged in on the keycloak server and redirect to the route. If a user is not logged in the server will redirect to the keycloak login page. User can create new accounts by clicking on the register link on the login page. This creates new users on the Keycloak server.



//route protected with Keycloak 
app.get(/test, keycloak.protect(), function(req, res){
    res.render(
        test, 
        {title:Test of the test}
        ); 
});


Enter fullscreen mode Exit fullscreen mode

Set the logout route to use keycloak middleware to kill the session.



app.use( keycloak.middleware( { logout: '/'} ));


Enter fullscreen mode Exit fullscreen mode

See the following for the full implementation of server.




'use strict';

const Keycloak = require('keycloak-connect');
const express = require('express');
const session = require('express-session');
const expressHbs = require('express-handlebars');

const app = express();


// Register 'handelbars' extension with The Mustache Express
app.engine('hbs', expressHbs({extname:'hbs',
  defaultLayout:'layout.hbs',
  relativeTo: __dirname}));
app.set('view engine', 'hbs');


var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });

//session
app.use(session({
  secret:'thisShouldBeLongAndSecret',
  resave: false,
  saveUninitialized: true,
  store: memoryStore
}));

app.use(keycloak.middleware());

//route protected with Keycloak
app.get('/test', keycloak.protect(), function(req, res){
  res.render('test', {title:'Test of the test'});
});

//unprotected route
app.get('/',function(req,res){
  res.render('index');
});

app.use( keycloak.middleware( { logout: '/'} ));

app.listen(8000, function () {
  console.log('Listening at http://localhost:8000');
});


Enter fullscreen mode Exit fullscreen mode

Installation of example

Clone this repo and cd to the new directory run npm install, there is some extra stuff like views in the repo.

Demo Video

You can see Keycloak and an Express.js server in action at
ScreenShot

Setup Keycloak Server

You will need to have a Keycloak server up and running to use this express application. Keycloak can be downloaded and run locally or can be run from a docker container see docker hub image for more info.

Download Keycloak at the download page .To run it locally unzip the downloaded file and run standalone.sh



./keycloak-unzip-directory/bin/standalone.sh


Enter fullscreen mode Exit fullscreen mode

You can then access the Keycloak server from a browser using the following url

http://localhost:8080/auth/
You will hit the initial password screen for Keycloak administrator .

For more information on setting up Keycloak see the following guide

Next you need to setup a Realm . Login in to Keycloak Admin Console and hover over top left hand corner and click on Add realm and give it a name.


create a realm

To use the Node.js adapter, first you must create a client for your application in the Keycloak Administration Console. Setup a Open ID Connect Client. In your new realm click on Clients and Create and give your client a name/ID.

The adapter supports public, confidential, and bearer-only access type. Which one to choose depends on the use-case scenario. In this case I picked public with openid-connect.

You will need to define a valid redirect URL

Once the client is created click the Installation tab, select Keycloak OIDC JSON for Format Option, and then click Download.

The downloaded keycloak.json file should be placed at the root folder of your project. Sample keycloak.json file



{
  "realm": "test",
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "keycloak-express", 
  "public-client": true,
  "confidential-port": 0
}


Enter fullscreen mode Exit fullscreen mode

That’s it you will have your Express web routes protected by Keycloak .For more information see here.

Myblog

Top comments (6)

Collapse
 
austincunningham profile image
Austin Cunningham • Edited

Looks like Keycloak are deprecating keycloak-connect node client adapter used in this blog by the end of the year 2022 keycloak.org/2022/02/adapter-depre.... New blog here using openid-client dev.to/austincunningham/keycloak-e...

Collapse
 
drggcoolman profile image
JBef

One thing to look out for in Production: "Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing." from npmjs.com/package/express-session

Collapse
 
subu1979 profile image
KMV.Subramaniyam

Can you share the github repo of this example. Thanks

Collapse
 
austincunningham profile image
Austin Cunningham
Collapse
 
patel264 profile image
dharmendra patel

app.use(session({
secret:'thisShouldBeLongAndSecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));

What is the secret in this ?
it this the public key from keycloak

Collapse
 
austincunningham profile image
Austin Cunningham

Hi Dharmendra,
It's the express-sessions secret and is something you set yourself, see stackoverflow.com/questions/534313... or the original docs senchalabs.org/connect/session.html for more info.