Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
If you're having issues don't hesitate to reach out on Discord!
Let's install oidc-spa in your project:
npm install oidc-spayarn add oidc-spapnpm add oidc-spaCreate the silent-sso.htm file in your public directory:
Don't use logout({ redirectTo: "home" }) but explicitely tell where you want your users to be redirected after logout using logout({ redirectTo: "specific url", url: "/my-home" }) or use logout({ redirectTo: "current page" }).
bun add oidc-spa<!doctype html>
<html>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>Let's get your App authenticated!
import { createOidc } from "oidc-spa";
const oidc = await createOidc({
issuerUri: "https://auth.your-domain.net/realms/myrealm",
clientId: "myclient",
/**
This piece of code should give you the necessary information to understand how oidc-spa can be used inside your react components. To go further you can refer to the examples setup to see how to integrate oidc-spa with your routing library:
If you get your OIDC parameters from an API you can passes an assync function that returns the oidc parameters. This function gets called when <OidcProvider /> is first mounted or when getOidc() is first called.
xx
Feeling a bit lost? Have a question? A feature request? Reach out on Discrord!
import { createReactOidc } from "oidc-spa/react";
export const { OidcProvider, useOidc, getOidc } = createReactOidc({
// NOTE: If you don't have the params right away see note below.
issuerUri: "https://auth.your-domain.net/realms/myrealm",
clientId: "myclient",
/**
* Vite: `publicUrl: import.meta.env.BASE_URL`
* CRA: `publicUrl: process.env.PUBLIC_URL`
* Other: `publicUrl: "/"` (Usually)
*/
publicUrl: import.meta.env.BASE_URL
});
ReactDOM.createRoot(document.getElementById("root")!).render(
<OidcProvider
// Optional, it's usually so fast that a fallback is really not required.
fallback={<>Checking authentication ⌛️</>}
>
<App />
</OidcProvider>
);
function App() {
const { isUserLoggedIn, login, logout, oidcTokens } = useOidc();
return (
isUserLoggedIn ? (
<>
{/*
Note: The decodedIdToken can be typed and validated with zod See: https://github.com/keycloakify/oidc-spa/blob/fddac99d2b49669a376f9a0b998a8954174d195e/examples/tanstack-router/src/oidc.tsx#L17-L43
If you are wondering why ther's a decodedIdToken and no
decodedAccessToken read this: https://docs.oidc-spa.dev/resources/jwt-of-the-access-token
*/}
<span>Hello {oidcTokens.decodedIdToken.preferred_username}</span>
<button onClick={() => logout({ redirectTo: "home" })}>
Logout
</button>
</>
) : (
<button onClick={() => login({
/**
* If you are calling login() in the callback of a button click
* (like here) set this to false.
*/
doesCurrentHrefRequiresAuth: false
/**
* Optionally, you can add some extra parameter
* to be added on the login url.
* (Can also be a parameter of createReactOidc `extraQueryParams: ()=> ({ ui_locales: "fr" })`)
*/
//extraQueryParams: { kc_idp_hint: "google", ui_locales: "fr" }
/**
* You can allso set where to redirect the user after
* successful login
*/
// redirectUrl: "/dashboard"
/**
* Keycloak: You can also send the user direcly to the register page
* See: https://github.com/keycloakify/oidc-spa/blob/14a3777601c50fa69d1221495d77668e97443119/examples/tanstack-router-file-based/src/components/Header.tsx#L54-L66
*/
})} >
Login
</button>
)
);
}
import { useEffect, useState } from "react";
type Order = {
id: number;
name: string;
};
function OrderHistory(){
const { oidcTokens } = useOidc({ assertUserLoggedIn: true });
const [orders, setOrders] = useState<Order[] | undefined>(undefined);
useEffect(
()=> {
fetch("https://api.your-domain.net/orders", {
headers: {
Authorization: `Bearer ${oidcTokens.accessToken}`
}
})
.then(response => response.json())
.then(orders => setOrders(orders));
},
[]
);
if(orders === undefined){
return <>Loading orders ⌛️</>
}
return (
<ul>
{orders.map(order => (
<li key={order.id}>{order.name}</li>
))}
</ul>
);
}export const {
OidcProvide,
useOidc,
getOidc
} = createReactOidc(async ()=> {
const {
issuerUri,
clientId
} = await axios.get("/oidc-params").then(r => r.data);
return {
issuerUri,
clientId,
publicUrl: import.meta.env.BASE_URL
};
});For certain use cases, you may want a mock adapter to simulate user authentication without involving an actual authentication server.
This approach is useful when building an app where user authentication is a feature but not a requirement. It also proves beneficial for running tests or in Storybook environments.
import { createOidc } from "oidc-spa";
import { createMockOidc } from "oidc-spa/mock";
import { z } from "zod";
const decodedIdTokenSchema = z.object({
sub:
By default, oidc-spa saves tokens in session storage, allowing users to skip the silent sign-in process when they reload your app (CTRL + R). However, token persistence can be disabled, and everything will still function as expected. The only difference is that reloading the app may take slightly longer.
import { createOidc } from "oidc-spa";
const oidc = await createOidc({
// ...
doDisableTokenPersistence: true
});import { createReactOidc } from "oidc-spa/react";
export const {
OidcProvider,
useOidc
} = createReactOidc({
// ...
doDisableTokenPersistence: true
The example setup is live here: https://example-react-router.oidc-spa.dev/
Run it locally with:
git clone https://github.com/keycloakify/oidc-spa
mv oidc-spa/examples/react-router oidc-spa-react-router
rm -rf oidc-spa
cd oidc-spa-react-router
yarn
yarn devWhat happens if the OIDC server is down, or if the server indicates that your client configuration is not valid?
By default, if you don't have isAuthRequiredOnEveryPages set to true, when there is an error with the OIDC initialization your website will load with the user unauthenticated.
This allows the user to access parts of the application that do not require authentication. When the user clicks on the login button (triggering the login() function), a browser alert is displayed, indicating that authentication is currently unavailable, and no further action is taken.
You can customize this behavior. An initializationError object is present on the OIDC object if an error occurred.
You probably don't need to do it. The token refresh is handled automatically for you, however you can manually trigger a token refresh:
You can also track when the token are being refreshed:
Or directly in your component:
Very little change in the API.
The public/silent-sso.html -> to public/silent-sso.htm (without the l)
Use getOidc() instead or prOidc (React API)
Google is ending third-party cookies for all Chrome users in 2024 and are already disabled by default in Safari.
Let's see how it might affect you.
First of all, if your identity server and your app shares the same root domain you are not affected.
Example, if you are in the case:
Your app is hosted at www.example.com or dashboard.example.com
Vite + TypeScript + React + Tanstack Router
The example setup is live here:
Run it locally with:
import { createReactOidc } from "oidc-spa/react";
import { createMockReactOidc } from "oidc-spa/mock/react";
import { z } from "zod";
const decodedIdTokenSchema = z.object({
sub: z.string(),
preferred_username: z.string()
});
const publicUrl = import.meta.env.BASE_URL;
export const { OidcProvider, useOidc, getOidc } =
!import.meta.env.VITE_OIDC_ISSUER ?
createMockReactOidc({
isUserInitiallyLoggedIn: false,
publicUrl,
mockedTokens: {
decodedIdToken: {
sub: "123",
preferred_username: "john doe"
} satisfies z.infer<typeof decodedIdTokenSchema>
}
}) :
createReactOidc({
issuerUri: import.meta.env.VITE_OIDC_ISSUER,
clientId: import.meta.env.VITE_OIDC_CLIENT_ID,
publicUrl,
decodedIdTokenSchema
});import { createOidc } from "oidc-spa";
const oidc = await createOidc({ ... });
if( oidc.isUserLoggedIn ){
oidc.renewToken(
// Optionally you can pass extra params that will be added
// to the body of the POST request to the openid-connect/token endpoint.
// { extraTokenParams: { electedCustomer: "customer123" } }
// This parameter can also be provided as parameter to the createOidc
// function. See: https://github.com/keycloakify/oidc-spa/blob/59b8db7db0b47c84e8f383a86677e88e884887cb/src/oidc.ts#L153-L163
);
}import { useOidc } from "oidc";
import { useEffect } from "react";
function MyComponent(){
const { renewTokens } = useOidc({ assertUserLoggedIn: true });
useEffect(()=> {
renewTokens(
// Optionally you can pass extra params that will be added
// to the body of the POST request to the openid-connect/token endpoint.
// { extraTokenParams: { electedCustomer: "customer123" } }
// This parameter can also be provided as parameter to the createReactOidc
// function. See: https://github.com/keycloakify/oidc-spa/blob/59b8db7db0b47c84e8f383a86677e88e884887cb/src/oidc.ts#L153-L163
);
}, []);
return <>...</>;
}import { createOidc } from "oidc-spa";
const oidc = await createOidc({ ... });
if( !oidc.isUserLoggedIn ){
oidc.subscribeToTokensChange(() => {
console.log("Tokens change", oidc.getTokens());
});
}import { createReactOidc } from "oidc-spa/react";
export const {
/* ... */
getOidc
} = createReactOidc({ /* ... */ });
getOidc().then(oidc => {
if( !oidc.isUserLoggedIn ){
return;
}
oidc.subscribeToTokensChange(() => {
console.log("Tokens change", oidc.getTokens());
});
});import { useOidc } from "./oidc";
export function PotectedPage() {
const { oidcTokens } = useOidc({ assertUserLoggedIn: true});
useEffect(()=> {
console.log("Tokens changed", oidcTokens);
}, [oidcTokens]);
// ...
} import { createReactOidc } from "oidc-spa/react";
export const {
OidcProvider,
useOidc,
- prOidc,
+ getOidc
} = createReactOidc({ });
-prOidc.then(oidc => { /* ... */ });
+getOidc().then(oidc => { /* ... */ }); import { createOidc } from "oidc-spa";
import { createMockOidc } from "oidc-spa/mock";
import { z } from "zod";
const decodedIdTokenSchema = z.object({
sub: z.string(),
preferred_username: z.string()
});
const publicUrl= import.meta.env.BASE_URL;
const oidc = !import.meta.env.VITE_OIDC_ISSUER
- ? await createMockOidc({
+ ? await createMockOidc({
isUserInitiallyLoggedIn: false,
publicUrl,
mockedTokens: {
decodedIdToken: {
sub: "123",
preferred_username: "john doe"
} satisfies z.infer<typeof decodedIdTokenSchema>
}
})
: await createOidc({
issuerUri: import.meta.env.VITE_OIDC_ISSUER,
clientId: import.meta.env.VITE_OIDC_CLIENT_ID,
publicUrl
});import { createOidc } from "oidc-spa";
const oidc = await createOidc(...);
if( !oidc.isUserLoggedIn ){
// If the used is logged in we had no initialization error.
return;
Please note that due to browser security policies, it is impossible to distinguish whether the network is very slow or down, or if the OIDC server has rejected the configuration.
Consequently, one might encounter an error of type "bad configuration" on a slow 3G network, for example.
However, the timeout duration is automatically adjusted based on the speed of the internet connection of the user, which should prevent this issue from occurring.
Your identity server, for example Keycloak, is hosted at: auth.example.com
You are not affected ✅. Indeed Both www.example.com, dashboard.example.com and auth.example.com shares the same root domain: example.com. On the other end, if you are in the folowing case:
You app is hosted at www.examples.com or dashboard.example.com
Your identity server is hosted at: auth.sowhere-else.com
Let's see how third party cookies phase out will affect you:
You will see a console warning "Third-party cookie will be blocked" in the console in production.
If a user that is authenticated close the tab of your app or close the browser and open your site again a while later. With third party cookies enabled and assuming he's session haven't expired yet he will be automaticall logged in. With third party cookies disabled your website will load in unautenticated mode. If he clicks on the login button this will trigger a full reload and he will be authenticated without having to enter he's credential again.
Conex resources:
reCaptcha is not directly related to oidc-spa since the cookie it sets is on the thegister page (so outside of your app). Anyway, since it's a connex concern:
git clone https://github.com/keycloakify/oidc-spa
mv oidc-spa/examples/tanstack-router-file-based oidc-spa-tanstack-router
rm -rf oidc-spa
cd oidc-spa-tanstack-router
yarn
yarn devIn some cases, you might want to perform some operation to initialize the user's session. This could involve calling a special API endpoint or clearing some cached values in the local storage.
What you don't want, however, is to run this every time the user refreshes the page or when their session is restored.
To help you determine if the session should be initialized, you can leverage the authMethod property that is available when the user is logged in.
There are three possible values for the authMethod property:
"back from auth server": The user was redirected to the authentication server's login/registration page and then redirected back to the application. Assuming you are using Keycloak and if you have configured your Keycloak server as suggested in the configuration guide, this happens approximately once every 14 days, assuming the user is using the same browser and has not explicitly logged out. Of course, the 14-day session is just a good default if you don't want your user to go through the login process every day, but this is for you to decide. If you implement an Auto Logout mechanism, it will be, of course, much shorter.
"session storage": The user's authentication was restored from the browser session storage, typically after a page refresh. As soon as the user closes the tab, the session storage is cleared. Note that you can . Note as well that if you use this is the status you'll get.
"silent signin": The user was authenticated silently using an iframe to check the session with the authentication server. This happens most of the time when the user navigates to your app in a new tab and their session has not expired yet.
You can also do this in your React component (although it's maybe not the best approach)
Automatically logging out your user after a set period of inactivity on your app (they dont move the mouse or press any key on the keyboard for a while)
This is a policy that is enforced on the identity server.
The auto logout is defined by the lifespan of the refresh token.
For example, if you're using Keycloak and you want an auto disconnect after 10 minutes of inactivity you would set the SSO Session Idle to 10 minutes. See Keycloak configuration guide.
If you can't configure your identity provider you can still enforce auto logout like so:
import { createOidc } from "oidc-spa";
const oidc = await createOidc({
// ...
__unsafe_ssoSessionIdleSeconds: 10 * 60 // 10 minutes
//autoLogoutParams: { redirectTo: "current page" } // Default
Note that this parameter is marked as unsafe because what happens if the user closes the tab? He will be able to return a while back and still be logged in. oidc-spa can't enforce a security policy when it's not running. Only the identity server can.
Backers of the project
When your user is logged in, you can provide a link to redirect to Keycloak so they can manage their account.
There is thee main actions:
UPDATE_PASSWORD: Enables the user to change their password.
And why it's not supposed to be read on the client side.
You might be surprised or even frustrated by the fact that oidc-spa only provides the decoded id token but not the decoded access token.
Infact the access token is supposed to be opaque for the client application is to be used only as an authentication key such as a Bearer token for an API.
As per the OIDC standard the access token is not even required to be a JWT!
But worry not, everything that you need is probably in the id token, if there is something missing in your id token that is present in your access token there is an explicit policy on your identity server in place that strips this information out. Zod is stripping out all the claims that are not specified in the schema. This might have led you to believe that there is less information in the id token than what actually is.
If, however, you still want to access the informations in the access token you can do it with:
import { useOidc } from "oidc";
import { useEffect } from "react";
function LoginButton() {
const { isUserLoggedIn, login, initializationError } = useOidc();
useEffect(() => {
if (!initializationError) {
return;
}
console.warn("OIDC initialization error");
switch (initializationError.type) {
case "bad configuration":
console.warn("The identity server and/or the client is misconfigured");
break;
case "server down":
console.warn("The identity server is down");
break;
case "unknown":
console.warn("An unknown error occurred");
break;
}
}, []);
if (isUserLoggedIn) {
return null;
}
return (
<button onClick={() => {
if (initializationError) {
alert(`Can't login now, try again later: ${
initializationError.message
}`);
return;
}
login({ ... });
}}>
Login
</button>
);
}import { createOidc } from "oidc-spa";
const oidc = await createOidc({ /* ... */ });
if (oidc.isUserLoggedIn && oidc.isAuthMethod === "back from auth server") {
// Do something related to initialization or clearing cache
}import { createReactOidc } from "oidc-spa/react";
export const {
/* ... */
getOidc
} = createReactOidc({ /* ... */ });
getOidc().then(oidc => {
if( !oidc.isUserLoggedIn ){
return;
}
if( oidc.authMethod === "back from auth server" ){
// Do something related to initialization or clearing cache
}
});import { useOidc } from "./oidc";
import { useEffect } from "react";
function MyComponent(){
const { isUserLoggedIn, authMethod } = useOidc();
useEffect(()=> {
// Warning! In dev mode, when React Strict Mode is enabled
// this will be called twice!
if( !isUserLoggedIn ){
return;
}
if( authMethod === "back from auth server" ){
// Do something related to initialization or clearing cache
}
}, []);
}import { createReactOidc } from "oidc-spa/react";
export const {
OidcProvider,
useOidc
} = createReactOidc({
// ...
__unsafe_ssoSessionIdleSeconds: 10 * 60 // Ten minutes
//autoLogoutParams: { redirectTo: "current page" } // Default
//autoLogoutParams: { redirectTo: "home" }
//autoLogoutParams: { redirectTo: "specific url", url: "/a-page" }
});UPDATE_PROFILE: Enable the user to edit teir account information such as first name, last name, email, and any additional user profile attribute that you might have configured on your Keycloak server.
delete_account: (In lower case): This enables the user to delete he's account. You must enable it manually on your Keycloak server Admin console. See Keycloak Configuration Guide.
Let's, as an example, how you would implement an update password button:
import { createOidc } from "oidc-spa";
const oidc = await createOidc({ ... });
if( oidc.isUserLoggedIn ){
// Function to invoke when the user click on your "change my password" button.
const
import { decodeJwt } from "oidc-spa/tools/decodeJwt";
const decodedAccessToken = decodeJwt(oidc.getTokens().accessToken);import { decodeJwt } from "oidc-spa/tools/decodeJwt";
const { oidcTokens } = useOidc();
const decodedAccessToken = decodeJwt(oidcTokens.accessToken);If there is no part of your app that can be accessed without being logged it you can make oidc-spa automatically redirect your users to the login pages when they are not authenticated.
Note that in this mode you don't have to check isUserLoggedIn (you know it's true), or useOidc({ assertUserLoggedIn: true })(you know that's the case).
import { createOidc, OidcInitializationError } from "oidc-spa";
try{
const oidc = await createOidc({
// ...
isAuthGloballyRequired: true,
import { createReactOidc } from "oidc-spa/react";
export const {
OidcProvider,
useOidc,
prOidc
} = createReactOidc
import { OidcProvider } from "oidc";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<OidcProvider
Enable the admin of your application to login as a given user.
User impersonation should ideally be managed by the authentication server. For instance, if you are using Keycloak, you can navigate to the Admin Console, then go to: Users -> Action -> Impersonate. This allows you to access all applications within the realm as the impersonated user.
The workaround described in this documentation is intended for situations where:
const { unsubscribeFromAutoLogoutCountdown } = oidc.subscribeToAutoLogoutCountdown(
({ secondsLeft }) => {
if( secondsLeft === undefined ){
console.log("Countdown reset, the user moved");
return;
}
if( secondsLeft > 60 ){
return;
}
console.log(`${secondsLeft} before auto logout`)
}
);function ProtectedPage() {
// Here we can safely assume that the user is logged in.
const { goToAuthServer, backFromAuthServer } = useOidc({ assertUserLoggedIn: true });
return (
<>
<button
onClick={() =>
goToAuthServer({
extraQueryParams: { kc_action: "UPDATE_PASSWORD" }
})
}
>
Change password
</button>
{/*
Optionally you can display a feedback message to the user when they
are redirected back to the app after completing or canceling the
action.
*/}
{backFromAuthServer?.extraQueryParams.kc_action === "UPDATE_PASSWORD" && (
<p>
{(()=>{
switch(backFromAuthServer.result.kc_action_status){
case "success":
return "Password successfully updated";
case "cancelled":
return "Password unchanged";
}
})()}
</p>
)}
</>
);
}
The support team handling impersonation does not have access to the Keycloak Admin Console.
Hosting a custom admin app under a subpath of the authentication server's URL is not an option.
Imagine you have a custom admin app that allows your support team to impersonate users. With oidc-spa, you can include a special query parameter when redirecting a support team member from your admin app to your main app. This will automatically authenticates the support team member as the impersonated user.
By default, this feature is disabled. To enable it:
import { createOidc } from "oidc-spa";
const oidc = await createOidc({
// ...
getDoContinueWithImpersonation: async ({ parsedAccessToken })=> {
const
import { createReactOidc } from "oidc-spa/react";
export const { OidcProvider, useOidc, getOidc } = createReactOidc({
// ...
getDoContinueWithImpersonation: async ({ parsedAccessToken })=>
After using the Keycloak API to obtain an access token, ID token, and refresh token for a user session in exchange for your admin token, you can craft the redirection URL for impersonation as follows:
(For this example, we assume you're using a JavaScript backend, but you can easily adapt it to your environment.)
The primary usecase for a library like oidc-spa is to use it to authenticate a REST, tRPC, or Websocket API.
Let's see a very basic REST API example:
Initialize oidc-spa and expose the oidc instance as a promise:
import { createOidc } from "oidc-spa";
export const prOidc = createOidc({/* ... */});Create a REST API Client that adds the OIDC Access Token as Autorization header to every HTTP request:
import axios from "axios";
import { prOidc } from "oidc";
type Api = {
getTodos: () => Promise<{ id
Initialize the React adapter of oidc-spa and expose the prOidc object, a promise of the vanilla OIDC API:
Create a REST API Client that adds the OIDC Access Token as Autorization header to every HTTP request:
Using your REST API client in your REACT components:
If you're implementing a JavaScript Backend (Node/Deno/webworker) oidc-spa also exposes an utility to help you validate and decode the access token that your client sends in the authorization header. Granted, this is fully optional feel free to use anything else. Let's assume we have a Node.js REST API build with Express or Hono. You can create an oidc file as such:
Then you can enforce that some endpoints of your API requires the user to be authenticated, in this example we use Hono:
If you're looking for a comprehensive Backend+Frontend example you can refer to Insee's project
The app is live here:
The frontend (Vite project):
The backend (Node TODO App REST API):
Let's spin up a Keycloak server and configure it for your webapp!
If you already have access to a Keycloak server you can skip this section.
Follow one of the following guides:
Don't want to deploy and maintain a own Keycloak server yourself?
Choosing Keycloak as a Service through a cloud IAM provider can offload the complexities of management and maintenance. It ensures that your system is always up-to-date with the latest security patches and features without the direct overhead of server upkeep. This is especially beneficial for teams prioritizing development and innovation over infrastructure management, offering robust support and service level agreements to guarantee smooth operation.
Let's configure your Keycloak server with good default for an SPA.
Connect to the admin panel of your Keycloak server (we assumes it's https://auth.my-domain.net/auth)
Create a realm called "myrealm" (or something else), go to Realm settings
On the tab General
User Profile Enabled: On
Now the parameter that you will have to provide to oidc-spa are:
Replace your-domain.net, myrealm and myclient by what you actually used in the configuration process.
(On older Keycloak the issuerUri will be "https://auth.your-domain.net/auth/realms/myrealm")
const accessToken = "...";
const idToken = "...";
const refreshToken = "...";
const obj = {
accessToken,
idToken,
refreshToken,
};
// NOTE: An array in case you have more than one oidc client instance in your app.
const arr = [obj];
const str = JSON.stringify(arr);
const b64 = btoa(str); // to base64
// This is the impersonation url:
const url = `https://your-app.com?oidc-spa_impersonate=${b64}`import { createReactOidc } from "oidc-spa/react";
export const {
OidcProvider,
useOidc,
getOidc
} = createReactOidc(/* ... */);import axios from "axios";
import { getOidc } from "oidc";
type Api = {
getTodos: () => Promise<{ id: number; title: string; }[]>;
addTodo: (todo: { title: string; }) => Promise<void>;
};
const axiosInstance = axios.create({ baseURL: import.meta.env.API_URL });
axiosInstance.interceptors.request.use(async config => {
const oidc= await getOidc();
if( !oidc.isUserLoggedIn ){
throw new Error("We made a logic error: The user should be logged in at this point");
}
config.headers.Authorization = `Bearer ${oidc.getTokens().accessToken}`;
return config;
});
export const api: Api = {
getTodo: ()=> axiosInstance.get("/todo").then(response => response.data),
addTodo: todo => axiosInstance.post("/todo", todo).then(response => response.data)
};import { api } from "../api";
type Todo= {
id: number;
title: string;
};
function UserTodos(){
const [todos, setTodos] = useState<Todo[] | undefined>(undefined);
useEffect(
()=> {
api.getTodos().then(todos => setTodos(todos));
},
[]
);
if(todos === undefined){
return <>Loading your todos items ⌛️</>
}
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}On the tab login
User registration: On
Forgot password: On
Remember me: On, or Off if you want to implement auto logout.
On the tab email, we give an example with AWS SES, if you don't have a SMTP server at hand you can skip this by going to Authentication (on the left panel) -> Tab Required Actions -> Uncheck "set as default action" Verify Email. Be aware that with email verification disable, anyone will be able to sign up to your service.
From: [email protected]
Host: email-smtp.us-east-2.amazonaws.com
Port: 465
Authentication: enabled
Username: **************
Password: ***************************************
When clicking "save" you'll be asked for a test email, you have to provide one that correspond to a pre-existing user or you will get a silent error and the credentials won't be saved.
On the tab Themes. See Keycloakify for creating a Keycloak theme that match your webapp.
On the tab Localization
Internationalization: Enabled
Supported locales: <Select the languages you wish to support>
On the tab Sessions
SSO Session Idle: 14 days - This is where you configure the auto logout policy. This parameter defines the lifespawn of the refresh token. If you want your user to be automatically loged out after 30 minutes of inactivity, Inacivity meaning they are not actively interacting with your app by scrolling, moving the mouse or typing, then you want to set this to 30 minutes.
SSO Session Max: 14 days - Even if you implement auto logout you want to leave this to at least one day. Indeed as long as your users are actively interacting with your app they should remain logged in**.**
SSO Session Idle Remember Me: 365 days - Same than SSO Session Idle but when the user have checked "Remember me" when login in. If you have enaled "remeber me" and you want this option to make sens you must set it to a value that is greater than SSO Session Idle. If you have set SSO Session Idle to something short because you want to implement an auto logout policy you probably want to go in Realm -> login and disable "Remember me"
SSO Session Max Remember Me: 365 days - Same note here.
Create a new OpenID Connect client called "myclient" (or something else) by accessing Clients -> Create Client
Root URL: https://your-domain.net (or something else, your app does not need to be on the
the same domain as your Keycloak).
Valid redirect URIs: https://onyxia.my-domain.net/*, http://localhost* (for testing in local)
Web origins: *
Login theme: keycloak (or your theme if you have one)
(OPTIONAL) In Authentication (on the left panel) -> Tab Required Actions enable and set as default action Terms and Conditions. (You can use Keycloakify to specify your terms and conditions, see next section)
(OPTIONAL) On the left pannel you can go to identity provider to enable login via Google, GitHub, Instagram, ect...
(OPTIONAL) Enable your user to delete their own account (see user account managment)
In the left bar navigate to Autentication -> Required Action -> "Delete Account" Enabled: On
In the left bar navigate to Realm Setting -> User Registration -> Default Roles -> Assign Role -> Filter by client -> select Delete Account and click on assign.
issuerUri: "https://auth.your-domain.net/realms/myrealm",
clientId: "myclient"import { createOidcBackend } from "oidc-spa/backend";
import { z } from "zod";
import { HTTPException } from "hono/http-exception";
export async function createDecodeAccessToken() {
const oidcIssuerUri = process.env.OIDC_ISSUER
if (oidcIssuerUri === undefined) {
throw new Error("OIDC_ISSUER must be defined in the environment variables")
}
const { verifyAndDecodeAccessToken } = await createOidcBackend({
issuerUri: oidcIssuerUri,
decodedAccessTokenSchema: z.object({
sub: z.string(),
realm_access: z.object({
roles: z.array(z.string())
})
// Some other info you might want to read from the accessToken, example:
// preferred_username: z.string()
})
});
function decodeAccessToken(params: {
authorizationHeaderValue: string | undefined;
requiredRole?: string;
}) {
const { authorizationHeaderValue, requiredRole } = params;
if( authorizationHeaderValue === undefined ){
throw new HTTPException(401);
}
const result = verifyAndDecodeAccessToken({
accessToken: authorizationHeaderValue.replace(/^Bearer /, "")
});
if( !result.isValid ){
switch( result.errorCase ){
case "does not respect schema":
throw new Error(`The access token does not respect the schema ${result.errorMessage}`);
case "invalid signature":
case "expired":
throw new HTTPException(401);
}
}
const { decodedAccessToken } = result;
if(
requiredRole !== undefined &&
!decodedAccessToken.ream_access.roles.includes(requiredRole)
){
throw new HTTPException(401);
}
return decodedAccessToken;
}
return { decodeAccessToken };
}import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import { serve } from "@hono/node-server"
import { HTTPException } from "hono/http-exception";
import { getUserTodoStore } from "./todo";
import { createDecodeAccessToken } from "./oidc";
(async function main() {
const { decodeAccessToken } = await createDecodeAccessToken();
const app = new OpenAPIHono();
{
const route = createRoute({
method: 'get',
path: '/todos',
responses: {/* ... */}
});
app.openapi(route, async c => {
const decodedAccessToken = decodeAccessToken({
authorizationHeaderValue: c.req.header("Authorization")
});
if (decodedAccessToken === undefined) {
throw new HTTPException(401);
}
const todos = getUserTodoStore(decodedAccessToken.sub).getAll();
return c.json(todos);
});
}
const port = parseInt(process.env.PORT);
serve({
fetch: app.fetch,
port
})
console.log(`\nServer running. OpenAPI documentation available at http://localhost:${port}/doc`)
})();