Acutally implement a login in the demo app
This commit is contained in:
@ -1,11 +1,63 @@
|
||||
import "./App.css";
|
||||
import logo from "./logo.svg";
|
||||
import myimg from "./myimg.png";
|
||||
import { createOidcClientProvider, useOidcClient } from "./oidc";
|
||||
import { addFooToQueryParams, addBarToQueryParams } from "../keycloak-theme/valuesTransferredOverUrl";
|
||||
import { Evt } from "evt";
|
||||
import { id } from "tsafe/id";
|
||||
import jwt_decode from "jwt-decode";
|
||||
|
||||
const { OidcClientProvider } = createOidcClientProvider({
|
||||
url: "https://auth.code.gouv.fr/auth",
|
||||
realm: "keycloakify",
|
||||
clientId: "starter",
|
||||
log: console.log,
|
||||
//The login pages will be in english.
|
||||
getUiLocales: () => "en",
|
||||
transformUrlBeforeRedirect: url =>
|
||||
[url]
|
||||
//Instead of foo and bar you could have isDark for example or any other state that you wish to
|
||||
//transfer from the main app to the login pages.
|
||||
.map(url => addFooToQueryParams({ url, value: { foo: 42 } }))
|
||||
.map(url => addBarToQueryParams({ url, "value": "value of bar transferred to login page" }))
|
||||
[0],
|
||||
// An event emitter that posts whenever the user interacts with the app
|
||||
// This is to tell if we should allow the token to expires.
|
||||
evtUserActivity:
|
||||
Evt.merge([
|
||||
Evt.from(document, "mousemove"),
|
||||
Evt.from(document, "keydown")
|
||||
]).pipe(() => [id<void>(undefined)]),
|
||||
});
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<OidcClientProvider>
|
||||
<ContextualizedApp />
|
||||
</OidcClientProvider>
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
function ContextualizedApp() {
|
||||
|
||||
const { oidcClient } = useOidcClient();
|
||||
|
||||
return (
|
||||
<div className="App">
|
||||
<header className="App-header">
|
||||
{
|
||||
oidcClient.isUserLoggedIn ?
|
||||
<>
|
||||
<h1>You are authenticated</h1>
|
||||
<pre>{JSON.stringify(jwt_decode(oidcClient.accessToken))}</pre>
|
||||
<button onClick={() => oidcClient.logout({ redirectTo: "home" })}>Logout</button>
|
||||
</>
|
||||
:
|
||||
<>
|
||||
<button onClick={() => oidcClient.login({ doesCurrentHrefRequiresAuth: false })}>Login</button>
|
||||
</>
|
||||
}
|
||||
<img src={logo} className="App-logo" alt="logo" />
|
||||
<img src={myimg} alt="test_image" />
|
||||
<p style={{ "fontFamily": '"Work Sans"' }}>Hello world</p>
|
||||
|
206
src/App/oidc.tsx
Normal file
206
src/App/oidc.tsx
Normal file
@ -0,0 +1,206 @@
|
||||
import { useState, useContext, createContext, useEffect } from "react";
|
||||
import keycloak_js from "keycloak-js";
|
||||
import { id } from "tsafe/id";
|
||||
import { addParamToUrl } from "powerhooks/tools/urlSearchParams";
|
||||
import type { ReturnType } from "tsafe/ReturnType";
|
||||
import type { Param0 } from "tsafe/Param0";
|
||||
import { assert } from "tsafe/assert";
|
||||
import { createKeycloakAdapter } from "keycloakify";
|
||||
import type { NonPostableEvt } from "evt";
|
||||
import jwt_decode from "jwt-decode";
|
||||
|
||||
export declare type OidcClient = OidcClient.LoggedIn | OidcClient.NotLoggedIn;
|
||||
|
||||
export declare namespace OidcClient {
|
||||
export type NotLoggedIn = {
|
||||
isUserLoggedIn: false;
|
||||
login: (params: {
|
||||
//To prevent infinite loop if the user click login then cancel.
|
||||
doesCurrentHrefRequiresAuth: boolean;
|
||||
}) => Promise<never>;
|
||||
};
|
||||
|
||||
export type LoggedIn = {
|
||||
isUserLoggedIn: true;
|
||||
//NOTE: It changes when renewed, don't store it.
|
||||
accessToken: string;
|
||||
logout: (params: { redirectTo: "home" | "current page" }) => Promise<never>;
|
||||
updateTokenInfo: () => Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
type Params = {
|
||||
url: string;
|
||||
realm: string;
|
||||
clientId: string;
|
||||
transformUrlBeforeRedirect: (url: string) => string;
|
||||
evtUserActivity: NonPostableEvt<void>;
|
||||
getUiLocales: () => string;
|
||||
log?: typeof console.log;
|
||||
};
|
||||
|
||||
async function createKeycloakOidcClient(params: Params): Promise<OidcClient> {
|
||||
const {
|
||||
url,
|
||||
realm,
|
||||
clientId,
|
||||
transformUrlBeforeRedirect,
|
||||
evtUserActivity,
|
||||
getUiLocales,
|
||||
log
|
||||
} = params;
|
||||
|
||||
const keycloakInstance = keycloak_js({ url, realm, clientId });
|
||||
|
||||
let redirectMethod: ReturnType<
|
||||
Param0<typeof createKeycloakAdapter>["getRedirectMethod"]
|
||||
> = "overwrite location.href";
|
||||
|
||||
const isAuthenticated = await keycloakInstance
|
||||
.init({
|
||||
"onLoad": "check-sso",
|
||||
"silentCheckSsoRedirectUri": `${window.location.origin}/silent-sso.html`,
|
||||
"responseMode": "query",
|
||||
"checkLoginIframe": false,
|
||||
"adapter": createKeycloakAdapter({
|
||||
"transformUrlBeforeRedirect": url =>
|
||||
[url].map(transformUrlBeforeRedirect).map(
|
||||
url =>
|
||||
addParamToUrl({
|
||||
url,
|
||||
"name": "ui_locales",
|
||||
"value": getUiLocales()
|
||||
}).newUrl
|
||||
)[0],
|
||||
keycloakInstance,
|
||||
"getRedirectMethod": () => redirectMethod
|
||||
})
|
||||
})
|
||||
.catch((error: Error) => error);
|
||||
|
||||
//TODO: Make sure that result is always an object.
|
||||
if (isAuthenticated instanceof Error) {
|
||||
throw isAuthenticated;
|
||||
}
|
||||
|
||||
const login: OidcClient.NotLoggedIn["login"] = async ({
|
||||
doesCurrentHrefRequiresAuth
|
||||
}) => {
|
||||
if (doesCurrentHrefRequiresAuth) {
|
||||
redirectMethod = "location.replace";
|
||||
}
|
||||
|
||||
await keycloakInstance.login({ "redirectUri": window.location.href });
|
||||
|
||||
return new Promise<never>(() => { });
|
||||
};
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return id<OidcClient.NotLoggedIn>({
|
||||
"isUserLoggedIn": false,
|
||||
login
|
||||
});
|
||||
}
|
||||
|
||||
const oidcClient = id<OidcClient.LoggedIn>({
|
||||
"isUserLoggedIn": true,
|
||||
"accessToken": keycloakInstance.token!,
|
||||
"logout": async ({ redirectTo }) => {
|
||||
await keycloakInstance.logout({
|
||||
"redirectUri": (() => {
|
||||
switch (redirectTo) {
|
||||
case "current page":
|
||||
return window.location.href;
|
||||
case "home":
|
||||
return window.location.origin;
|
||||
}
|
||||
})()
|
||||
});
|
||||
|
||||
return new Promise<never>(() => { });
|
||||
},
|
||||
"updateTokenInfo": async () => {
|
||||
await keycloakInstance.updateToken(-1);
|
||||
|
||||
oidcClient.accessToken = keycloakInstance.token!;
|
||||
}
|
||||
});
|
||||
|
||||
(function callee() {
|
||||
const msBeforeExpiration =
|
||||
jwt_decode<{ exp: number }>(oidcClient.accessToken)["exp"] * 1000 - Date.now();
|
||||
|
||||
setTimeout(async () => {
|
||||
log?.(
|
||||
`OIDC access token will expire in ${minValiditySecond} seconds, waiting for user activity before renewing`
|
||||
);
|
||||
|
||||
await evtUserActivity.waitFor();
|
||||
|
||||
log?.("User activity detected. Refreshing access token now");
|
||||
|
||||
const error = await keycloakInstance.updateToken(-1).then(
|
||||
() => undefined,
|
||||
(error: Error) => error
|
||||
);
|
||||
|
||||
if (error) {
|
||||
log?.("Can't refresh OIDC access token, getting a new one");
|
||||
//NOTE: Never resolves
|
||||
await login({ "doesCurrentHrefRequiresAuth": true });
|
||||
}
|
||||
|
||||
oidcClient.accessToken = keycloakInstance.token!;
|
||||
|
||||
callee();
|
||||
}, msBeforeExpiration - minValiditySecond * 1000);
|
||||
})();
|
||||
|
||||
return oidcClient;
|
||||
}
|
||||
|
||||
const minValiditySecond = 25;
|
||||
|
||||
|
||||
const oidcClientContext = createContext<OidcClient | undefined>(undefined);
|
||||
|
||||
export function createOidcClientProvider(params: Params) {
|
||||
|
||||
|
||||
const prOidcClient = createKeycloakOidcClient(params);
|
||||
|
||||
function OidcClientProvider(props: { children: React.ReactNode; }) {
|
||||
|
||||
const { children } = props;
|
||||
|
||||
const [oidcClient, setOidcClient] = useState<OidcClient | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
prOidcClient.then(setOidcClient);
|
||||
|
||||
}, []);
|
||||
|
||||
if (oidcClient === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<oidcClientContext.Provider value={oidcClient}>
|
||||
{children}
|
||||
</oidcClientContext.Provider>
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
return { OidcClientProvider };
|
||||
|
||||
}
|
||||
|
||||
export function useOidcClient() {
|
||||
const oidcClient = useContext(oidcClientContext);
|
||||
assert(oidcClient !== undefined);
|
||||
return { oidcClient };
|
||||
}
|
@ -5,6 +5,9 @@ import { useI18n } from "./i18n";
|
||||
import Fallback, { defaultKcProps, type KcProps, type PageProps } from "keycloakify";
|
||||
import Template from "./Template";
|
||||
import DefaultTemplate from "keycloakify/lib/Template";
|
||||
import { foo, bar } from "./valuesTransferredOverUrl";
|
||||
|
||||
console.log(`Values passed by the main app in the URL parameter:`, { foo, bar });
|
||||
|
||||
const Login = lazy(()=> import("./pages/Login"));
|
||||
// If you can, favor register-user-profile.ftl over register.ftl, see: https://docs.keycloakify.dev/realtime-input-validation
|
||||
|
123
src/keycloak-theme/valuesTransferredOverUrl.ts
Normal file
123
src/keycloak-theme/valuesTransferredOverUrl.ts
Normal file
@ -0,0 +1,123 @@
|
||||
import { kcContext } from "./kcContext";
|
||||
import {
|
||||
retrieveParamFromUrl,
|
||||
addParamToUrl,
|
||||
updateSearchBarUrl
|
||||
} from "powerhooks/tools/urlSearchParams";
|
||||
import { capitalize } from "tsafe/capitalize";
|
||||
|
||||
export const { foo, addFooToQueryParams } = (() => {
|
||||
const queryParamName = "foo";
|
||||
|
||||
type Type = { foo: number; };
|
||||
|
||||
const value = (()=> {
|
||||
|
||||
const unparsedValue = read({ queryParamName });
|
||||
|
||||
if( unparsedValue === undefined ){
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return JSON.parse(unparsedValue) as Type;
|
||||
|
||||
})();
|
||||
|
||||
function addToUrlQueryParams(params: {
|
||||
url: string;
|
||||
value: Type;
|
||||
}): string {
|
||||
const { url, value } = params;
|
||||
|
||||
return addParamToUrl({
|
||||
url,
|
||||
"name": queryParamName,
|
||||
"value": JSON.stringify(value)
|
||||
}).newUrl;
|
||||
}
|
||||
|
||||
const out = {
|
||||
[queryParamName]: value,
|
||||
[`add${capitalize(queryParamName)}ToQueryParams` as const]: addToUrlQueryParams
|
||||
} as const;
|
||||
|
||||
return out;
|
||||
})();
|
||||
|
||||
export const { bar, addBarToQueryParams } = (() => {
|
||||
const queryParamName = "bar";
|
||||
|
||||
type Type = string;
|
||||
|
||||
const value = (()=> {
|
||||
|
||||
const unparsedValue = read({ queryParamName });
|
||||
|
||||
if( unparsedValue === undefined ){
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return JSON.parse(unparsedValue) as Type;
|
||||
|
||||
})();
|
||||
|
||||
function addToUrlQueryParams(params: {
|
||||
url: string;
|
||||
value: Type;
|
||||
}): string {
|
||||
const { url, value } = params;
|
||||
|
||||
return addParamToUrl({
|
||||
url,
|
||||
"name": queryParamName,
|
||||
"value": JSON.stringify(value)
|
||||
}).newUrl;
|
||||
}
|
||||
|
||||
const out = {
|
||||
[queryParamName]: value,
|
||||
[`add${capitalize(queryParamName)}ToQueryParams` as const]: addToUrlQueryParams
|
||||
} as const;
|
||||
|
||||
return out;
|
||||
})();
|
||||
|
||||
|
||||
function read(params: { queryParamName: string }): string | undefined {
|
||||
if (kcContext === undefined || process.env.NODE_ENV !== "production") {
|
||||
//NOTE: We do something only if we are really in Keycloak
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { queryParamName } = params;
|
||||
|
||||
read_from_url: {
|
||||
const result = retrieveParamFromUrl({
|
||||
"url": window.location.href,
|
||||
"name": queryParamName
|
||||
});
|
||||
|
||||
if (!result.wasPresent) {
|
||||
break read_from_url;
|
||||
}
|
||||
|
||||
const { newUrl, value: serializedValue } = result;
|
||||
|
||||
updateSearchBarUrl(newUrl);
|
||||
|
||||
localStorage.setItem(queryParamName, serializedValue);
|
||||
|
||||
return serializedValue;
|
||||
}
|
||||
|
||||
//Reading from local storage
|
||||
const serializedValue = localStorage.getItem(queryParamName);
|
||||
|
||||
if (serializedValue === null) {
|
||||
throw new Error(
|
||||
`Missing ${queryParamName} in URL when redirecting to login page`
|
||||
);
|
||||
}
|
||||
|
||||
return serializedValue;
|
||||
}
|
Reference in New Issue
Block a user