Auto Login
Enforce authentication everywhere in your app.
Auto Login is a mode in oidc-spa designed for applications where every page requires authentication.
This is typically the case for admin dashboards or any internal tool that do not need "marketing" pages.
When Auto Login is enabled, visiting your application automatically redirects the user to the IdP’s login page if no active session is detected.
import { createOidc } from "oidc-spa/core";
const oidc = await createOidc({
// ...
autoLogin: true
}); import { oidcSpa } from "oidc-spa/react-tanstack-start";
export const {
bootstrapOidc,
useOidc,
getOidc,
oidcFnMiddleware,
oidcRequestMiddleware,
- enforceLogin
} = oidcSpa
.withExpectedDecodedIdTokenShape({ /* ... */ })
.withAccessTokenValidation({ /* ... */ })
+ .withAutoLogin()
.createUtils();import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";
import Header from "@/components/Header";
import { AutoLogoutWarningOverlay } from "@/components/AutoLogoutWarningOverlay";
import { useOidc } from "@/oidc";
export const Route = createRootRoute({
// ...
shellComponent: ShellComponent,
// NOTE: Even with SSR disabled here, the ShellComponent is still SSR'd.
// Only page components lose SSR.
// You *can* disable SSR per-page for routes that load authed data,
// but if your app isn’t public, it’s simpler to SSR only the shell.
ssr: false
});
function ShellComponent({ children }: { children: React.ReactNode }) {
const { isOidcReady } = useOidc();
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<div className="min-h-screen flex flex-col">
<Header />
<main className="flex flex-1 flex-col">
{isOidcReady &&
children
}
</main>
</div>
<AutoLogoutWarningOverlay />
<Scripts />
</body>
</html>
);
}You can remove all the assertin your oidc component, the components specifically for the not logged in state can be removed.
You can remove the assert: "user logged in" from oidcFnMiddleware and oidcRequestMiddleware:
You can remove all the beforeLoad: enforceLogin:
For all the components that are within the <OidcInitializationGate /> you know that hasInitCompleted will be true so you can assert it to narrow down the type:
You can then proceed to remove all the usage of withLoginEnforced and enforceLogin throughout your codebase.
You can also remove all the assetion of the login state of the user:
All the components with useOidc({ assert: "user not logged in" }); can be removed.
All the handling for the user not logged in state can be removed.
You can remove the usage of Oidc.enforceLoginGuard:
Last updated
Was this helpful?