OIDC SPA
GitHubHome
v4
  • Documentation
  • Release Notes & Upgrade Instructions
v4
  • Documentation
    • 🔩Installation
    • 👨‍🔧Basic Usage
    • 🔌Web API
    • ⏲️Auto Logout
    • ❗Error Management
    • 🎭Mock
    • 🔁Tokens Renewal
    • 🛡️Globally Enforce Authentication
    • 🔐User Account Management
    • 🔄Doing Something Only When a New Session is Created
  • Example setups
    • 🛣️TanStack Router
    • 🛤️React Router
  • Resources
    • 🔑Keycloak Configuration Guide
    • 👥Accessing Keycloak Groups
    • 🍪End of third-party cookies
    • 🗝️JWT Of the Access Token
    • 💬Discord Server
  • ⭐Sponsors
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Documentation

Globally Enforce Authentication

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,
   // Optional, the default value is: location.href (here)
   // postLoginRedirectUrl: "/dashboard"
});

}catch(error){
    const oidcInitializationError = error as OidcInitializationError;
    console.log(oidcInitializationError.message);
    console.log(oidcInitializationError.type); // "server down" | "bad configuration" | "unknown";
}
src/oidc.ts
import { createReactOidc } from "oidc-spa/react";

export const {
    OidcProvider,
    useOidc,
    prOidc
} = createReactOidc({
   // ...
   isAuthGloballyRequired: true,
   // Optional, the default value is: location.href (here)
   // postLoginRedirectUrl: "/dashboard"
});
src/main.tsx

import { OidcProvider } from "oidc";

ReactDOM.createRoot(document.getElementById("root")!).render(
    <React.StrictMode>
        <OidcProvider 
            ErrorFallback={({ initializationError })=>(
                <h1 style={{ color: "red" }}>
                    An error occurred while initializing the OIDC client:
                    {initializationError.message}
                    {initializationError.type} /* "server down" | "bad configuration" | "unknown"; */
                </h1>
            )}
        >
            {/* ... */}
        </OidcProvider>
    </React.StrictMode>
);
PreviousTokens RenewalNextUser Account Management

Last updated 9 months ago

Was this helpful?

🛡️