Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
The createOidc() function is a function that assists in creating an OpenID Connect (OIDC) client, which can be utilized in your application for authentication purposes.
params
: An object containing the following properties:
issuerUri: string
The URI of the OpenID Connect issuer.
clientId: string
The client ID assigned to your application.
transformUrlBeforeRedirect?: (url:string) => string
(Optional), A function that transforms the string URL before redirection.
getExtraQueryParams?: () => Record<string,string>
(Optional), A function that returns extra query parameters.
publicUrl?: string
(Optional), The public URL of your application, useful when your app is not hosted at the origin of the domain.
A Promise that resolves to an object of type Oidc
, which can be either Oidc.LoggedIn
or Oidc.NotLoggedIn
.
Oidc.LoggedIn
Represents a logged-in state.
isUserLoggedIn
: true
.
renewTokens: () => Promise<void>
A function to renew tokens.
getTokens: () => Tokens
: A function that returns the current tokens.
subscribeToTokensChange
A function to subscribe to token changes.
Params
onTokenChange: () => void
A function to execute when token changes
Returns
unsubscribe: () => void
logout
A function to log out.
Params
redirectTo: "home" | "current page"
to be redirected after logout to home or current page
OR redirectTo: "specific url", url: string
to be redirected to specific url
Returns
Promise<never>
Oidc.NotLoggedIn
Represents a not-logged-in state.
isUserLoggedIn
: false
.
login
A function to initiate the login process.
Params
doesCurrentHrefRequiresAuth
(boolean): Whether the current href requires authentication.
extraQueryParams
(optional, object): Extra query parameters for login.
Returns
Promise<never>
This promise never resolves because we are redirected to oidc web service
You can see a live preview of this example here
Let's install oidc-spa in your project:
Create the following file in your public directory:
A solution to implement user authentication in your webapplication
An OIDC client tailored for Single Page Applications, particularly suitable for Vite projects. This library is intended for scenarios such as integrating your application with Keycloak.
In straightforward terms, this library is ideal for those seeking to enable user login/registration in their web application. When used in conjunction with Keycloak (for example), it enables you to offer a modern and secure authentication experience with minimal coding effort. This includes options for signing in via Google, X, GitHub, or other social media platforms. We provide comprehensive guidance from beginning to end.
🎓 Accessible to all skill levels; no need to be an OIDC expert.
🛠️ Easy to set up; eliminates the need for creating special /login
/logout
routes.
🎛️ Minimal API surface for ease of use.
✨ Robust yet optional React integration.
📖 Comprehensive documentation and project examples: End-to-end solutions for authenticating your app.
✅ Best in class type safety: Enhanced API response types based on usage context.
While oidc-client-ts
serves as a comprehensive toolkit, our library aims to provide a simplified, ready-to-use adapter that will pass any security audit and that will just work out of the box on any browser.
We utilize oidc-client-ts
internally but abstract away most of its intricacies.
Our library takes a modular approach to OIDC and React, treating them as separate concerns that don't necessarily have to be intertwined.
At its core, oidc-spa
is a straightforward adapter that isn't tied to any specific UI framework, making it suitable for projects that enforce a strict separation of concerns between the core logic of the application and the UI.
Additionally, we provide adapters for React and starter projects for integration with react-router-dom
or @tanstack/react-router
.
Beside the fact that this lib only works with Keycloak it is also likely to be deprecated.
Onyxia:
The French Interministerial Base of Free Software:
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 .
In the realm of web development, there are two prevailing philosophies. One camp of developers advocates for a strict separation of concerns, maintaining a clear distinction between the core logic of their application and their UI components. Conversely, others prefer to embed the logic of their application directly within their components, minimizing the conceptual gap between related elements.
Regardless of your preference, we've got you covered. In addition to the base API, we offer a React Context/Hook API designed for seamless integration within your component body, ensuring flexibility and ease of use no matter your development style.
If you are coding in vanilla or implementing the OIDC-SPA library in an application with a strict separation of concerns between your core logic and UI components, follow these steps:
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:
The token refresh is handled automatically for you, however you can manually trigger a token refresh with oidc.renewTokens()
.(or const { renewTokens } = useOidc({ assertUserLoggedIn: true }
);
If the OIDC server is down or misconfigured an error get printed in the console, everything continues as normal with the user unauthenticated. If the user tries to login an alert saying that authentication is not available at the moment is displayed and nothing happens. This enable your the part of your app that do not requires authentication to remain up even when your identities server is facing issues.
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
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
Login theme: keycloak (see next section to see how to create a theme for your app)
Email theme: keycloak
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 setting and the following two are so that when the user click "remember me" when he logs in, he doesn't have to login again for the next two weeks.
SSO Session Idle Remember Me: 14 days
SSO Session Max Remember Me: 14 days
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...
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.
By default, Keycloak comes with very generic login and register pages, you might want to customize them to match the design system of your App. We've createad a lib that let you create Keycloak theme using React!
On the tab email, we give an example with , 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.
You can see a live preview of this example here