Skip to content

Instantly share code, notes, and snippets.

@TimKochDev
Created December 6, 2024 10:48
Show Gist options
  • Save TimKochDev/5b17eec213fdc858c4e6d1aee6fb1f74 to your computer and use it in GitHub Desktop.
Save TimKochDev/5b17eec213fdc858c4e6d1aee6fb1f74 to your computer and use it in GitHub Desktop.
React authentication with Keycloak and oidc-client-ts. Redirect directly to Keycloak's registration page
// Note:
// - @react-keycloak/web is deprecated
// - Keycloak doesn't want to support their official JS adapter keycloak-js (https://www.keycloak.org/2022/02/adapter-deprecation.html)
// oidcConfig.ts
import {
UserManager,
WebStorageStateStore,
Log,
UserManagerSettings,
OidcClient,
} from "oidc-client-ts";
const settings: UserManagerSettings = {
authority: import.meta.env.VITE_OIDC_AUTHORITY,
client_id: import.meta.env.VITE_OIDC_CLIENT_ID,
post_logout_redirect_uri: import.meta.env.VITE_OIDC_POST_LOGOUT_REDIRECT_URI,
redirect_uri: import.meta.env.VITE_OIDC_REDIRECT_URI,
response_type: "code",
};
export const oidcUserManager = new UserManager(settings);
/**
* Use this only for low-level OIDC operations (e.g. creating sign-in requests
* but modifying the url). For most operations, use the `oidcUserManager`
* (probably via the `useOidcAuth` hook) instead.
*/
export const oidcClient = new OidcClient(settings);
// App.ts
import { AuthProvider as OidcProvider } from "react-oidc-context";
export const App = () => (
<OidcProvider
onSigninCallback={(user) => {
if (!user) return;
const state = user.state as { location?: string } | undefined;
const toLocation = state?.location || "/";
console.log("onSignInCallback redirecting to", toLocation);
history.replace(toLocation);
}}
userManager={oidcUserManager}
>
{/* */}
</OidcProvider />
)
// SignUpButton.tsx
import { oidcClient } from "../oidcConfig";
export const SignUpButton = (props: ButtonProps) => {
return (
<button
onClick={async () => {
const req = await oidcClient.createSigninRequest({});
// This really is the official way to redirect to the registration page
// See https://www.keycloak.org/docs/latest/server_admin/#_registration-rc-client-flows
// Note that oidcClient and oidcUserManager are different objects and don't seem to share state.
// Hence, when the user is redirected to this app the userManager doesn't know about the SigninRequest.
// It will therefore consider the user as not authenticated, redirect to keycloak again, which redirects back to the app.
// This time the userManager knows about the SigninRequest and considers the user authenticated.
window.location.href = req.url.replace("/auth", "/registrations");
}}
>
Sign Up
</button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment