πWeb API
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: 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 prOidc;
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)
};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:
Backend
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:
Comprehensive example
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):
Last updated
Was this helpful?