Follow these steps to create a Auth service using keycloak in Docker
1) Install Docker Desktop using https://www.docker.com/products/docker-desktop/
2) Create a Docker Network (Optional)
docker network create keycloak-network
3) Run Keycloak Container
docker run -d --name keycloak ^ -p 8080:8080 ^ -e KEYCLOAK_USER=admin ^ -e KEYCLOAK_PASSWORD=admin ^ --network keycloak-network ^ jboss/keycloak
4) Check Container Status:
docker ps
docker logs keycloak
5) Create a Docker Network (Optional)
docker network create keycloak-network
6) Access Keycloak Admin Console
Open a web browser and go to http://localhost:8080. Log in using the admin credentials (admin/admin).
7) Configure Keycloak Realm and Client
Create a Realm:
In the Keycloak Admin Console, click on "Add Realm" and set up a new realm with the desired settings.
Create a Client:
Within the created realm, go to "Clients" and click on "Create." Configure the client according to your application needs.
8) Integrate Keycloak in Your Application
npm install keycloak-connect express
Create a file named `server.js`:
const express = require('express');
const session = require('express-session');
const Keycloak = require('keycloak-connect');
const app = express();
const PORT = 3000;
const memoryStore = new session.MemoryStore();
app.use(session({
secret: 'my-secret',
resave: false,
saveUninitialized: true,
store: memoryStore,
}));
const keycloak = new Keycloak({ store: memoryStore });
app.use(keycloak.middleware());
app.get('/', keycloak.protect(), (req, res) => {
res.send('Hello, secured world!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
9) Run Your Application
node server.js
Access http://localhost:3000 in your browser
10) Install the express module,
npm init -y
npm install express keycloak-connect express-session
11) Running your Node.js application again
node server.js
12) Create a Keycloak Configuration File:
Create a file named keycloak.json in your project directory.
This file contains the configuration details for your Keycloak setup.
Here's a minimal example;
replace the placeholder values with your actual Keycloak configuration:
{
"realm": "your-realm-name",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "your-client-id",
"credentials": {
"secret": "your-client-secret"
},
"confidential-port": 0
}
Make sure the values for "realm", "auth-server-url", "resource", "credentials.secret", etc., match your Keycloak setup.
No comments:
Post a Comment