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
- General Information
- Getting Started with the Integration - Start Here!
- Module Exports - Functions and Types available from the module.
- Authentication Flow - How it works from login button click.
- 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
, andKeycloakWrapper
. - For use with @bcgov/keycloak-express
- 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",
- Add import
import { KeycloakProvider } from '@bcgov/keycloak-react';
tomain.tsx
file or wherever thecreateRoot()
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>,
);
- Add import
import { KeycloakWrapper } from '@bcgov/keycloak-react';
toAppRouter.tsx
file or wherever your routes are defined. Wrap<KeycloakWrapper>
around Routes inside of Router like this example usingreact-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'.
- 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": "[email protected]",
"client_roles": ["admin"]
}
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';
The Keycloak Authentication system begins when the user visits the frontend application.
- The user visits the frontend of the application. Here, the
KeycloakWrapper
component initializes and checks the URL for a query parameter namedtoken
.
-
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.
-
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. -
Upon successful login at the Keycloak login page, Keycloak redirects the user to the
/oauth/login/callback
endpoint. -
The authentication code returned by the callback endpoint is used to retrieve the access token and the refresh token for the user.
-
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. -
The
KeycloakWrapper
component re-initiates and the process repeats from step 1, this time with thetoken
query parameter available.
Details
- keycloak-react
- bcgov
- over 1 year ago
- Apache-2.0
- 1 dependencies
Assets
- keycloak-react-1.0.0-alpha.2.tgz
Download activity
- Total downloads 3
- Last 30 days 0
- Last week 0
- Today 0