Skip to content
keycloak-react / 1.0.0-alpha.2

keycloak-react 1.0.0-alpha.2

Install from the command line:
Learn more about npm packages
$ npm install @bcgov/keycloak-react@1.0.0-alpha.2
Install via package.json:
"@bcgov/keycloak-react": "1.0.0-alpha.2"

About this version

BCGov SSO Keycloak Frontend Integration

Lifecycle:Experimental License

NodeJS Typescript React


Table of Contents

General Information

  • For React:18 on NodeJS:18
  • For Keycloak Gold Standard.
  • Works with Vanilla JavaScript or Typescript 5.
  • BY DEFUALT, set to work with a proxy pass to the backend using /api.
  • To use without a proxy pass, refer to the notes in the setup documentation below regarding optional parameters and property of getLoginURL, getLogoutURL, and KeycloakWrapper.
  • For use with @bcgov/keycloak-express

Getting Started with the Integration

  1. Add the following line to your frontend package.json under "dependencies"::
"@bcgov/keycloak-react": "https://github.com/bcgov/keycloak-react/releases/download/v1.0.0-alpha.1/bcgov-keycloak-react.tgz",

  1. Add import import { KeycloakProvider } from '@bcgov/keycloak-react'; to main.tsx file or wherever the createRoot() function is. Wrap <KeycloakProvider> component around the Router or Routes like shown below:
import { KeycloakProvider } from '@bcgov/keycloak-react'; // <--------------------------------------
import { ThemeProvider } from '@mui/material';
import AppRouter from 'AppRouter';
import React from 'react';
import { createRoot } from 'react-dom/client';
import theme from 'theme';

const root = createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <React.StrictMode>
    <KeycloakProvider> // <--------------------------------------
      <ThemeProvider theme={theme}>
        <AppRouter />
      </ThemeProvider>
    </KeycloakProvider> // <--------------------------------------
  </React.StrictMode>,
);

  1. Add import import { KeycloakWrapper } from '@bcgov/keycloak-react'; to AppRouter.tsx file or wherever your routes are defined. Wrap <KeycloakWrapper> around Routes inside of Router like this example using react-router-dom:
<Router>
  <KeycloakWrapper> // <--------------------------------------
    <Header />
    <Routes>
      <Route
        path="/"
        element={<h1>Home</h1>}
      />
    </Routes>
    <Footer />
  </KeycloakWrapper> // <--------------------------------------
</Router>

Note: KeycloakWrapper has optional property backendURL (string), defaults to '/api'.


  1. Use the following example to implement a login and logout button.
import { useKeycloak } from '@bcgov/keycloak-react';

const HomePage = () => {
  // state is aliased as authState
  const { state: authState, getLoginURL, getLogoutURL } = useKeycloak();
  const user = authState.userInfo;

  return (
    <>
      {user ? (
        <>
          <p>
            Logged in as User: {user.given_name} {user.family_name}
          </p>
          <button onClick={() => (window.location.href = getLogoutURL())}>Logout</button>
        </>
      ) : (
        <button onClick={() => (window.location.href = getLoginURL())}>Login with IDIR</button>
      )}
    </>
  );
};

Note: getLoginURL and getLogoutURL have optional param 'backendURL' (string), defaults to '/api'.


For all user properties reference SSO Keycloak Wiki - Identity Provider Attribute Mapping.
Example IDIR state.userInfo object:

{
  "idir_user_guid": "W7802F34D2390EFA9E7JK15923770279",
  "identity_provider": "idir",
  "idir_username": "JOHNDOE",
  "name": "Doe, John CITZ:EX",
  "preferred_username": "a7254c34i2755fea9e7ed15918356158@idir",
  "given_name": "John",
  "display_name": "Doe, John CITZ:EX",
  "family_name": "Doe",
  "email": "john.doe@gov.bc.ca",
  "client_roles": ["admin"]
}

Return to Top


Module Exports

These are the functions and types exported by the @bcgov/keycloak-react module.

import {
  KeycloakWrapper, // Provides the login and refresh token functionality.
  KeycloakProvider, // Provides state management for Keycloak.
  useKeycloak, // See below for usage.
  AuthContext, // Shouldn't need to be used in your code.
} from '@bcgov/keycloak-react';

// Use the useKeycloak() hook within a React component:
const {
  state, // Access the current user with state.userInfo
  getLoginURL, // Returns the login route. Optional param 'options' (object)
               // which includes 'backendURL' (string) and 'idpHint':
               // ("idir" | "bceidbasic" | "bceidbusiness" | "bceidboth" | "githubbcgov" | "githubpublic").
  getLogoutURL, // Returns the logout route. Optional param 'backendURL' (string).
  getAuthorizationHeader, // Returns the value for the 'Authorization' header when making requests to protected endpoints.
  hasRole, // Pass a role in the form of a string to tell if the user has the given client_role.
  setUserInfo, // Shouldn't need to be used in your code.
  refreshAccessToken, // Shouldn't need to be used in your code. Optional property 'backendURL' (string).
} = useKeycloak();

// Typescript Types - these shouldn't need to be used in your code.
import {
  AuthStateWithDispatch,
  AuthActionType,
  AuthState,
  AuthAction,
} from '@bcgov/keycloak-react';

Return to Top


Authentication Flow

The Keycloak Authentication system begins when the user visits the frontend application.

  1. The user visits the frontend of the application. Here, the KeycloakWrapper component initializes and checks the URL for a query parameter named token.
  • If the token query parameter is found:

    • The component strips the URL of the access token.
    • The user's information is set into the state using the token.
    • The user can now access the frontend of the application.
  • If the token query parameter is not found, the component checks if the user is logged in by using the refresh token to get a new access token by communicating with the /api/oauth/token endpoint.

    • If the refresh token exists and is valid, the user can now access the frontend of the application without seeing the login button, as their session is authenticated through the refresh token.
    • If the refresh token doesn't exist or is invalid, the login button is displayed.
  1. When the user clicks the login button, they are routed to the /api/oauth/login endpoint via a proxy pass, which then redirects them to the Keycloak login page.

  2. Upon successful login at the Keycloak login page, Keycloak redirects the user to the /oauth/login/callback endpoint.

  3. The authentication code returned by the callback endpoint is used to retrieve the access token and the refresh token for the user.

  4. The user is redirected back to the frontend with the access token included as a token query parameter and the refresh token set as an httpOnly cookie.

  5. The KeycloakWrapper component re-initiates and the process repeats from step 1, this time with the token query parameter available.

Return to Top

Details


Assets

  • keycloak-react-1.0.0-alpha.2.tgz

Download activity

  • Total downloads 3
  • Last 30 days 0
  • Last week 0
  • Today 0

Recent versions

View all