With your setup involving Docker, Keycloak, Apollo Server, GraphQL Nexus, Prisma ORM, and PostgreSQL, you need to ensure that each component interacts seamlessly to achieve user synchronization. Here's how you can effectively synchronize users from Keycloak into your PostgreSQL database:
Setup Overview
- Keycloak: This serves as your identity provider, issuing JWTs for authentication.
- Apollo Server: Used for your GraphQL API.
- Prisma ORM: Interface for interacting with your PostgreSQL database.
- PostgreSQL: Your database where user data will be stored.
Implementation Steps
-
Keycloak Configuration:
- Ensure your Keycloak is configured to issue JWTs that contain necessary user information (like user ID, email) in claims.
- Use the Keycloak Admin Console to manage user roles and access permissions.
-
Authentication Middleware:
- Create middleware for token verification and user synchronization.
You must verify the JWT using Keycloak's public keys and perform the user sync operation in your middleware or resolver functions.
-
Apollo GraphQL Setup:
- Use Apollo Server to set up your GraphQL API, integrating the middleware.
-
Prisma Integration:
- Use Prisma to define your user model and provide functionalities to find and create a user in your PostgreSQL database.
Example Code Snippet
Here's an example of how these steps might come together in your application setup:
1. Middleware for Token Verification and User Sync
// Apollo Server with middleware for JWT verification and user synchronization
const jwt = require('jsonwebtoken');
const { createServer } = require('@graphql-yoga/node');
const prisma = require('./prisma'); // Adjust your import path
// Middleware function
async function verifyJwtAndSyncUser(req, res, next) {
try {
const token = req.headers.authorization.split(' ')[1];
const publicKey = await getKeycloakPublicKey(); // Implement this logic to fetch Keycloak's public key
const decodedToken = jwt.verify(token, publicKey);
const { sub: keycloakUserId, email } = decodedToken;
// Sync user with Prisma ORM
let user = await prisma.user.findUnique({
where: { keycloakUserId },
});
if (!user) {
user = await prisma.user.create({
data: {
keycloakUserId,
email,
},
});
}
req.user = user; // Add user to request context
next();
} catch (error) {
console.error('JWT verification failed:', error);
return res.status(401).json({ error: 'Unauthorized' });
}
}
// Apollo Server Setup
const server = createServer({
schema: /* Define your schema */,
context: ({ req }) => {
return { user: req.user };
},
plugins: [
{
onRequest({ request, response, execute }) {
return verifyJwtAndSyncUser(request, response, execute);
},
},
],
});
// Start server
server.start(() => {
console.log('Server is running on http://localhost:4000');
});
2. Prisma User Model
Ensure your Prisma schema (schema.prisma) includes the user model:
model User {
id Int @id @default(autoincrement())
keycloakUserId String @unique
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Deployment with Docker
- Make sure each service is running in separate containers.
- Use Docker Compose to bring up services together, e.g., Keycloak, Apollo service with Prisma, and PostgreSQL.
Here's a simple docker-compose.yml example of how you might configure your services:
version: '3.7'
services:
keycloak:
image: jboss/keycloak
environment:
- KEYCLOAK_USER=admin
- KEYCLOAK_PASSWORD=admin
ports:
- "8080:8080"
db:
image: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
api:
build: ./api # Path to your API definition with server and Prisma settings
depends_on:
- db
ports:
- "4000:4000"
volumes:
pgdata:
Following this setup ensures a systematic approach to syncing users with your database while verifying and authenticating users from Keycloak within your GraphQL API.