Skip to content

Instantly share code, notes, and snippets.

@gsandaru
Created January 4, 2020 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsandaru/5f3a500224baf35f3994db4f68032106 to your computer and use it in GitHub Desktop.
Save gsandaru/5f3a500224baf35f3994db4f68032106 to your computer and use it in GitHub Desktop.
NodeJS Client Setup KeyCloak

Imports

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

Configurations

    // Configure session
    
    var memoryStore =  new  session.MemoryStore();    
    var keycloak =  new  Keycloak({ store: memoryStore });
    
    app.use(
      session({
        secret: "mySecret",
        resave: false,
        saveUninitialized: true,
        store: memoryStore
      })
    );
    
    // Attach middleware
    
    app.use(keycloak.middleware());

Public Route

    app.get("/", (req,  res,  next) => {    
	    res.json({ status:  "Public Endpoint" });    
    });

Protected Route

keycloak.protect() - middleware to check authenticated users

    app.get("/user/whoami", keycloak.protect(), (req, res, next) => {
      console.log(req.kauth.grant.access_token.content);
    
      let userinfo = { 
        name: req.kauth.grant.access_token.content.name, 
        email: req.kauth.grant.access_token.content.email, 
      };
    
      res.json(userinfo);
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment