Keycloak Node.JS without sessions – Stack Overflow

I’m trying to implement keycloak authentication on a NodeJS with Keycloak. I want to use JWT into the Authorization request header or in a request cookie.

I follewed the doc but it uses express-session. So the request does not contains JWT but the ID of the session on the server matching with the JWT.
I don’t want to use sessions but only JWT attached to the client request.

This is the code I’ve done:

const express = require("express");
const expressSession = require("express-session");
const keycloak = require("keycloak-connect");
const cors = require("cors");

const server = express();
const port = "80";

server.set("port",port);
server.use(express.json());
server.use(express.urlencoded());
server.use(cors());

const memoryStore = new expressSession.MemoryStore();

server.use(expressSession({
    secret: "keySecret",
    resave: false,
    saveUninitialized: true,
    store: memoryStore
}));

const KK = new keycloak({store: memoryStore});

server.use(KK.middleware({
    admin: "/admin",
    logout: "/"
}));

server.get("/private",KK.protect(),async (req,res,next)=> {
    res.json({message: "Hey! You're connected !"});
});


server.get("/public",(req,res,netx)=>{
    res.json({message: "This is the public page of the testing web app"});
});

server.listen(port,()=> {console.log("Server running on port "+port)});

Thanks !

Read more here: Source link