Remix
View a live deployed version.
We will use the Phase Two Remix example code here, but the logic could easily be applied to any existing application.
- Clone the Phase Two example repo.
- Open the Remix folder within
/frameworks/remix
. - Run
npm install
and thennpm run dev -- --port 3000
. This example leverages remix-auth and remix-keycloak to provide HOC support. - Open the
app/services/keycloak.server.ts
file. This is a server only file. We will be updating a few values from the prior section where we set up our OIDC client. Taking the values from the OIDC Client Config section, set those values in the code. While it is recommended to use Environment variables for the secret, for the purpose of this tutorial, paste in the Client secret from the OIDC client creation section for the value ofclientSecret
:
const kcConfig = {
useSSL: true,
domain: "usw2.auth.ac/auth",
realm: "shared-deployment-001",
clientID: "reg-example-1",
clientSecret: "CLIENT_SECRET", // Paste "Client secret" here. Use Environment variables in prod
callbackURL: "http://localhost:3000/auth/keycloak/callback",
};
Those are used to popluate the config for the KeycloakStrategy
:
export default new KeycloakStrategy(kcConfig, ({ profile }) => profile);
The config is then used with the Authenticator instance in the app/services/auth.server.ts
file. The authenticator instance uses the Session Storage to manage the state of authentication via a cookie.
import { Authenticator } from "remix-auth";
import keycloakServer from "./keycloak.server";
import { sessionStorage } from "~/services/session.server";
export const authenticator = new Authenticator(sessionStorage);
authenticator.use(keycloakServer);
At this point our entire application will be able to access all information and methods needed to perform authentication. View the session.server.ts
file for additional information about how the SessionStorage
is used. The SessionStorage
stores the Keycloak token and is used to derive the authenticated state. View user.tsx
for exactly how the code is authenticating your user. The sections rendering the Log in and Log out buttons are conditional areas based on the authenticated context. The buttons invoke server-side APIs provided by remix-auth
.
The logic using the authenticator to conditionally determine the Authenticated state, can be used to secure routes, components, and more.
-
Open localhost:3000. You will see the Phase Two example landing page. You current state should be Not authenticated. Click Log In. This will redirect you to your login page.
infoUse the non-admin user created in the previous section to sign in.
-
Enter the credentials of the non-admin user you created. Click Submit. You will then be redirected to the application. The Phase Two example landing page now loads your Authenticated state, displaying your user's email and name.
-
Neat! If you clear the browser state for that tab, then you will have to be redirected away to sign-in again.