Migrating from Keycloak-js
Polyfilling keycloak-js with oidc-spa
2
Update your codebase
-import Keycloak from "keycloak-js";
+import { Keycloak } from "oidc-spa/keycloak-js";
-import KeycloakAuthorization from "keycloak-js/authz";
+import { KeycloakAuthorization } from "oidc-spa/keycloak-js-authz";
// ...
await keycloak.init({
onLoad: 'check-sso',
- silentCheckSsoRedirectUri: `${location.origin}/silent-check-sso.html`,
//NOTE: fragment will be used. Conflict with your app logic routing
//is structuraly impossible in oidc-spa so there is no reason to
//support query.
- responseMode: "query",
// ...
});
// In oidc-spa the auth state is immutable and can be either:
// - Not established yet: keycloak.didInitialize is false
// - User is logged in: keycloak.authenticated is true
// - User is not logged in: keycloak.authenticated is false
// The value of keycloak.authenticated will never change without a full app reload.
// If you want to redirect to a specific page after logout call:
// keycloak.logout({ redirectUri: "/bye" })
-keycloak.onAuthLogout(()=> {});
// With oidc-spa you'll never end-up in a state where calling this makes sense.
-keycloak.clearToken();
// oidc-spa handles this internally.
-keycloak.onAuthRefreshError(); 3
4
Enable Security Features
import { defineConfig } from "vite";
import { oidcSpa } from "oidc-spa/vite-plugin";
export default defineConfig({
plugins: [
// ...
oidcSpa({
// See: https://docs.oidc-spa.dev/v/v10/security-features/browser-runtime-freeze
browserRuntimeFreeze: {
enabled: true
//exclude: [ "fetch", "XMLHttpRequest"]
},
// See: https://docs.oidc-spa.dev/v/v10/security-features/dpop
DPoP: {
enabled: true,
mode: "auto"
}
})
]
});5
(OPTIONAL) Display a Warning Before Auto Logout
import { Keycloak } from "oidc-spa/keycloak-js";
const keycloak = new Keycloak({ ... });
await keycloak.init({
...
// Optionally, customize the behavior of where the user gets redirected
// when their session expires.
// autoLogoutParams: { redirectTo: "current page" } // Default
// autoLogoutParams: { redirectTo: "home" }
// autoLogoutParams: { redirectTo: "specific url", url: "/your-session-has-expired" }
// autoLogoutParams: {
// redirectTo: "specific url",
// get url(){ return `/your-session-has-expired?return_url=${encodeURIComponent(location.href)}`; }
// }
});
// You can only access this property after keycloak.init() has resolved.
const oidc = keycloak.oidc;Last updated
Was this helpful?