Configurer un client dans Keycloak
Chaque application est enregistree comme "client" dans Keycloak.
Le flux OAuth2 Authorization Code
Flux d'authentification OIDC :
Utilisateur Application Keycloak
| | |
|-- Accede a app --> | |
| |-- Redirige vers -->|
| | /auth/realms/... |
|<-- Page de login ----------------------|
|-- Saisit login/mdp ------------------>|
| |<-- Code auth ------|
| |-- Echange code --> |
| |<-- Token JWT ------|
|<-- Page protegee --| |
| | |
Le token JWT contient :
- sub: identifiant unique
- email: adresse email
- realm_access.roles: ["developer", "viewer"]
- exp: date d'expiration
Integrer Keycloak avec GitLab
# Dans GitLab : Admin > Settings > Sign-in restrictions
# Ajouter un provider OIDC :
# gitlab.rb (configuration Omnibus)
gitlab_rails['omniauth_providers'] = [
{
name: "openid_connect",
label: "Keycloak",
args: {
name: "openid_connect",
scope: ["openid", "profile", "email"],
response_type: "code",
issuer: "https://auth.example.com/realms/devops-platform",
client_auth_method: "query",
discovery: true,
uid_field: "preferred_username",
client_options: {
identifier: "gitlab",
secret: "gitlab-client-secret",
redirect_uri: "https://gitlab.example.com/users/auth/openid_connect/callback"
}
}
}
]
Integrer Keycloak avec Grafana
# grafana.ini
[auth.generic_oauth]
enabled = true
name = Keycloak
allow_sign_up = true
client_id = grafana
client_secret = grafana-client-secret
scopes = openid profile email
auth_url = https://auth.example.com/realms/devops-platform/protocol/openid-connect/auth
token_url = https://auth.example.com/realms/devops-platform/protocol/openid-connect/token
api_url = https://auth.example.com/realms/devops-platform/protocol/openid-connect/userinfo
role_attribute_path = contains(realm_access.roles[*], 'admin') && 'Admin' || 'Viewer'
Proteger une API avec un token JWT
# Verifier le token dans une application (exemple Node.js/Express)
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const client = jwksClient({
jwksUri: 'https://auth.example.com/realms/devops-platform/protocol/openid-connect/certs'
});
app.use('/api', (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Token manquant' });
// Verifier et decoder le JWT
jwt.verify(token, getKey, { algorithms: ['RS256'] }, (err, decoded) => {
if (err) return res.status(403).json({ error: 'Token invalide' });
req.user = decoded;
next();
});
});
Securite : Keycloak gere aussi le MFA (Multi-Factor Authentication), le brute-force protection, et les politiques de mots de passe. Activez-les en production.