This is a Strapi plugin to support Keycloak (and more generally: OpenID Connect) authentication for end-users. It is not designed for admin users.
To configure Keycloak, see this guide. If you use another Identity Provider (IdP), see the documentation of your provider.
Install the plugin in your Strapi project:
npm install @tongquntech/strapi-plugin-keycloak --save
Enable the plugin in config/plugins.js (create the file if it does not exist so far):
module.exports = {
keycloak: {
enabled: true,
},
};
Create config/keycloak.js and configure Keycloak (or your other OIDC IdP) accordingly:
const fs = require("fs");
const yaml = require("js-yaml");
const fileContent = fs.readFileSync("config.yaml", "utf-8");
const configObj = yaml.load(fileContent);
module.exports = {
// client ID configured in Keycloak
clientId: configObj.keycloak.clientId,
// if the client access type is set to "confidential" in keycloak, add the client secret here. otherwise, don't set this value.
clientSecret: configObj.keycloak.clientSecret,
// auth endpoint, right value comes from Keycloak
authEndpoint: configObj.keycloak.authEndpoint,
// token endpoint, right value comes from Keycloak
tokenEndpoint: configObj.keycloak.tokenEndpoint,
// user info endpoint, right value comes from Keycloak
userinfoEndpoint: configObj.keycloak.userinfoEndpoint,
// logout endpoint, right value comes from Keycloak
logoutEndpoint: configObj.keycloak.logoutEndpoint,
// resource endpoint, right value comes from Keycloak
resourceEndpoint: configObj.keycloak.resourceEndpoint,
// redirect URI after Keycloak login, should be the full URL of the Strapi instance and always point to the `keycloak/callback` endpoint
redirectUri: configObj.keycloak.redirectUri,
// default URL to redirect to when login process is finished. In normal cases, this would redirect you back to the application using Strapi data
redirectToUrlAfterLogin: configObj.keycloak.redirectToUrlAfterLogin,
// setting these allows the client to pass a `redirectTo` query parameter to the `login` endpoint. If the `redirectTo`
// parameter is permitted by this array, after login, Strapi will redirect the user to it. Leave empty to disable
// the functionality.
permittedOverwriteRedirectUrls:
configObj.keycloak.permittedOverwriteRedirectUrls,
// URL to redirect to after logout
redirectToUrlAfterLogout: configObj.keycloak.redirectToUrlAfterLogout,
// set the threshold for auto refresh: if a request comes in and the access token is about to
// expire in less than this timespan (noted in milliseconds), it will be refreshed.
autoRefreshMsBeforeExpiry: configObj.keycloak.autoRefreshMsBeforeExpiry,
// enable debug messages in server log
debug: configObj.keycloak.debug,
};
/config.yaml accordingly:
database:
host: 192.168.71.121
port: 5432
name: postgres
username: postgres
password: TQcps123
schema: public
ssl: false
keycloak:
clientId: dam
clientSecret: Rma3cvFWyAmfHlAsMh5Wj70bedNdbs7F
authEndpoint: https://key.i3s.yhlcps.com/realms/dam/protocol/openid-connect/auth
tokenEndpoint: https://key.i3s.yhlcps.com/realms/dam/protocol/openid-connect/token
userinfoEndpoint: https://key.i3s.yhlcps.com/realms/dam/protocol/openid-connect/userinfo
logoutEndpoint: https://key.i3s.yhlcps.com/realms/dam/protocol/openid-connect/logout
resourceEndpoint: https://key.i3s.yhlcps.com/realms/dam/authz/protection/resource_set
redirectUri: http://localhost:1337/keycloak/callback
redirectToUrlAfterLogin: http://localhost:1337
permittedOverwriteRedirectUrls:
- http://localhost:1337
- http://localhost:8001
redirectToUrlAfterLogout: http://localhost:1337/keycloak/login
autoRefreshMsBeforeExpiry: 30 * 60 * 1_000
debug: true
To protect a route, apply the middleware to that route in api/[content-type]/routes/[content-type].js
(in our example todo
).
const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = {
routes: [
{
method: "POST",
path: "/modelInfo/getAssetsTree",
handler: "model-info.getAssetsTree",
config: {
auth: false,
middlewares: ["plugin::keycloak.keycloak"],
},
},
],
};
Restart Strapi.
Open http://localhost:1337/keycloak/login to start the login process.
Now open the find
endpoint of your content type, in this example http://localhost:1337/api/todos.
Strapi introduced API Tokens in version 4, which are meant to allow bypassing other means of authorization when set. The middleware takes API tokens into account. If a valid API token is set, there will be no check for a valid Keycloak login.
To check if the user is currently logged in with a valid access token, you can call the /keycloak/isLoggedIn
endpoint. It will return true
or false
.
The plugin supports refreshing the access token using refresh tokens:
You can manually call the /keycloak/refresh
endpoint with a GET
request. The plugin will use the refresh token stored in the user's session.
fetch("http://localhost:1337/keycloak/refresh", { credentials: "include" });
The plugin will then update the tokens in the user's session.
You can enable auto refresh in the config:
module.exports = {
// set the threshold for auto refresh: if a request comes in and the access token is about to
// expire in less than this timespan (noted in milliseconds), it will be refreshed.
autoRefreshMsBeforeExpiry: 30 * 60 * 1_000,
};
The refreshed access, ID and refresh tokens are automatically stored in the session.
Using the /keycloak/profile
route, you can fetch the user's keycloak profile:
fetch("http://localhost:1337/keycloak/profile", { credentials: include })
.then((res) => res.json())
.then((profile) => console.log(profile));
// {"sub":"deab236b-db26-4b25-afa9-ce5132503afe","email_verified":true,"name":"John Doe","preferred_username":"john.doe","given_name":"John","family_name":"Doe"}
By default, the plugin will check for the current login status by calling Keycloak's userinfo
endpoint. For Strapi instances with many requests, this can become a performance bottleneck.
You can change this behavior by providing your IdP's public key or a JWKS URI, which allows the plugin to verify and decode the access and ID tokens provided by your IdP. Like that, the plugin will not contact Keycloak anymore to verify the user's login status, but rely on the verification status of the access and ID tokens.
To enable token verification using a public key, define the jwtPublicKey
configuration property in config/keycloak.js
:
module.exports = {
jwtPublicKey: "Iadoghdsgh...",
};
You can find the public key in Keycloak under "Realm Settings" in the "Keys" tab. Look for the "RSA"-type public key with a "SIG" use, and click the "Public key" button to retrieve the public key.
If your IdP uses a non-default algorithm to sign tokens, you can define it with jwtAlgorithm
:
module.exports = {
jwtAlgorithm: "RS256",
};
If you don't set jwtAlgorithm
, it defaults to RS256
.
If your IdP provides a JWKS URI for token verification, you can set it in the config:
module.exports = {
jwksUri: "https://my-jwks-uri.com/keys",
};
The plugin will fetch the keys from the given URL and use them to verify the tokens.
When a user is logged in, the middleware will populate ctx.state.keycloak.profile
with the current user's profile.
console.log("The current user is ", ctx.state?.keycloak?.profile);
The user profile is made up of:
- The payload of the access token,
- the payload of the ID token,
- the response of the "user info" endpoint.
The plugin takes care of retrieving tokens (access token, ID token, refresh token) from the IdP. These tokens then are stored in the user's session using koa-session
, which Strapi uses as its underlying session management library.
You can access the tokens in the session:
{
accessToken,
idToken,
refreshToken,
} = ctx.session.keycloak;
To initiate a logout, redirect the user to /keycloak/logout
.
You can append a redirectTo
query parameter to forward the user to a custom URL:
http://localhost:1337/keycloak/logout?redirectTo=http://myfrontend/login
If none is specified, the user will be redirected to redirectToUrlAfterLogout
defined in the configuration.
You can optionally provide lifecycle hooks via the configuration:
module.exports = {
onLoginSuccessful: (ctx) => console.log("Login was successful"),
onLoginFailed: (ctx) => console.log("Login failed"),
};
These functions receive the full Koa context and can interact with it.
Additionally, you can use onRetrieveProfile
to enrich the user profile returned by the /profile
endpoint with custom information:
module.exports = {
onRetrieveProfile: (ctx) => ({ customGreeting: "hello" }),
};
The returned object will be merged with the user profile retrieved from the IdP.
You can use afterRetrieveProfile
which will be called after the profile has been retrieved from the IdP and after onRetrieveProfile
has been called. It gets both the context and the fetched user profile handed over as arguments.
module.exports = {
afterRetrieveProfile: (ctx, userProfile) => {
userProfile.randomField = "randomValue";
},
};
The canLogin
hook is called after a successful OIDC authentication and when the user profile has been fetched. The function is provided with the user profile as an argument. If it returns true
, a session is opened for the user. If it returns false
, the login process is aborted.
This hook is useful to allow or deny users access to your entire application based on profile information (e.g. group membership).
If the hook isn't set, all users with a valid OIDC login can login and create sessions.
module.exports = {
canLogin: async (userProfile) => {
return userProfile.groups?.includes("members");
},
};
The plugin implements the default OpenID Connect Authorization Code Flow. That's why it works with other Identity Providers than Keycloak, too. We have tested it with Auth0 and Azure Active Directory the login process works seamlessly.
The package name is somewhat misleading therefore -- we might change it to reflect the broader IdP support in the future.
One common reason for this is that the access and ID tokens supplied by your identity provider are very long. Strapi uses koa-session
for session management, and koa-session
stores all session information in a client-side browser cookie. Browser cookies have length limits, and if your tokens exceed that length limit, Strapi will fail to create a session.
As a solution, we recommend to use an external session store. See the koa-session
documentation for details.
A primitive implementation in the Strapi session middleware config that we do not recommend for production could looks like this:
const sessionStore = new Map<string, { session: unknown; expires: number }>();
export default [
{
name: "strapi::session",
config: {
store: {
async get(key: string) {
const sessionInfo = sessionStore.get(key);
if (!sessionInfo) {
return;
}
if (sessionInfo.expires < +new Date()) {
return;
}
return sessionInfo.session;
},
async set(key: string, session: unknown, maxAge: number) {
sessionStore.set(key, {
session,
expires: +new Date() + maxAge * 1000,
});
},
async destroy(key) {
sessionStore.delete(key);
},
},
},
},
];
This plugin can be easily used to implement login flows in React using our React Auth Context library.