Nodejs express router and get api Authentication Using Keycloak



Im going to explain in this post how to setup keycloak to protect your express router and get apis. first of all lets dig little bit around keycloak and express. 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.

Setup Keycloak Server.

1. Download Keycloak docker file
2. Run Keycloak docker image.
   docker run -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin  -p 8080:8080 jboss/keycloak
3. Access to keycloak using this url http://localhost:8080/auth/
User name and pass word is : admin
4. Create a new Realm. Ex: "express-demo".
5. Under created realm create a client. Ex : "express-work-demo" .
6. under setting tab provide these details.
client protocol = openid-connect
access type = public
valid redirect urls = http://localhost:8000/*
7. Once the client is created click the Installation tab, select Keycloak OIDC JSON for Format Option, and then click Download.
8. The downloaded keycloak.json file should be placed at the root folder of your project. This is sample keycloak.json file

Setup Express application

1. install keycloak-connect npm in your express application use the following command
  npm i keycloak-connect
2. You need to import keycloak-connect and express-sessions into your express application.

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


4. You can then use keycloak.protect on your protected routes . If you are access from Web 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 is complete Project Structure

App.js complete code

api.js complete code

if you need to use postman to make api request first you need to request Bearer token from keycloak then you can add the token to authenticate header to make api request to secured resources.
This is how you make Bearer Token request.



Copy Access Token then add it to postman request Authorization header


Comments

  1. nice informative post. Thanks you for sharing.
    We are an experienced team in one of the Best software company and product specialist for software development and implementation.
    Wordpress Development

    NodeJS Development

    ReplyDelete

Post a Comment

Popular Posts