Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
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:
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.
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.
What happens if the OIDC server is down, or if the server indicates that your client configuration is not valid?
By default, , 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.
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.
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:
Create a REST API Client that adds the OIDC Access Token as Autorization header to every HTTP request:
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 get your App authenticated!
In this guide, we assume that you have an OIDC-enabled authentication server in place, such as Keycloak.
If you have not yet set up such a server, please refer to .
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.
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).
In this section we assume the reader is using Keycloak. If you are using another kind of authentication server you'll have to addapt the queryParameter provided.
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.
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 .
Let's, as an example, how you would implement an update password button:
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:
In 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 , 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 , 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.
"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)
This example is purposefully very basic to minimize noise but in your App you should consider using (if you have JS backend) and .
Before starting be aware that oidc-spa does not yet support Next.js projects.
If you are using Next the closer alternative is to use NextAuth.js (with the Keycloak adapter if you are using Keycloak). You can refer to the phase two guide.
If you're having issues don't hesitate to reach out on Discord!
Let's install oidc-spa in your project:
Create the following file in your public directory:
TL;DR; It's mostly inconsequential.
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
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:
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:
Vite + TypeScript + React + Tanstack Router
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
On the tab login
User registration: On
Forgot password: On
Remember me: On
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: noreply@my-domain.net
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. If you want your user to be automatically loged out after 30 minutes, set it here.
SSO Session Max: 14 days
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 Therms and Conditions. (You can use Keycloakify to specify your therme and condition, 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.
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")
Friend of the project
Feeling a bit lost? Have a question? A feature request? Reach out on Discrord!