@tabui/react-security
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Getting Started with TabUI React Security Module

Integrations

React

TabUI React Security for Web requires:

  • React 16.0 or later
  • keycloak-js 9.0.2 or later

The maximum version allowed by keycloak-js compatible with RH-SSO 7.1 is 9.0.2.

yarn add @tabui/react-security

or

npm  install --save @tabui/react-security

Getting Started

Setup Keycloak instance

Create a keycloak.ts file in the src\config folder of your project (where App.js is located) with the following content

import Keycloak from "keycloak-js";

// Setup Keycloak Configuration instance as needed 
const config:Keycloak.KeycloakConfig = {
    url: process.env.REACT_APP_AUTH_SERVER_URL,
    realm: process.env.REACT_APP_AUTH_REALM ?? '',
    clientId: process.env.REACT_APP_AUTH_CLIENT_ID ?? '',    
}

// Pass initialization options as required
const keycloak = Keycloak(config);

export default keycloak;

Setup KeycloakProvider

The next step is to wrap your App inside ReactKeycloakProvider and pass the keycloak instance as prop

import keycloak from './config/keycloak'
import { ReactKeycloakProvider } from '@tabui/react-security';

// Wrap everything inside KeycloakProvider
const App = () => {
  return (
    <ReactKeycloakProvider authClient={keycloak}>...</ReactKeycloakProvider>
  )
}

N.B. If your using other providers (such as react-redux) it is recommended to place them inside ReactKeycloakProvider.

ReactKeycloakProvider automatically invokes keycloak.init() method when needed and supports the following props:

  • initOptions, contains the object to be passed to keycloak.init() method, by default the following is used

    {
      onLoad: 'check-sso',
    }
    

    for more options see Keycloak docs.

  • LoadingComponent, a component to be displayed while keycloak is being initialized, if not provided child components will be rendered immediately. Defaults to null

  • isLoadingCheck, an optional loading check function to customize LoadingComponent display condition. Return true to display LoadingComponent, false to hide it.

    Can be implemented as follow

    ;(keycloak) => !keycloak.authenticated
  • onEvent, an handler function that receives events launched by keycloak, defaults to null.

    It can be implemented as follow

    ;(event, error) => {
      console.log('onKeycloakEvent', event, error)
    }

    Published events are:

    • onReady
    • onInitError
    • onAuthSuccess
    • onAuthError
    • onAuthRefreshSuccess
    • onAuthRefreshError
    • onTokenExpired
    • onAuthLogout
  • onTokens, an handler function that receives keycloak tokens as an object every time they change, defaults to null.

    Keycloak tokens are returned as follow

    {
      "idToken": string,
      "refreshToken": string,
      "token": string
    }

Hook Usage

When a component requires access to Keycloak, you can use the useKeycloak Hook.

import { useKeycloak } from '@tabui/react-security'

export default () => {
  // Using Object destructuring
  const { keycloak, initialized } = useKeycloak()

  // Here you can access all of keycloak methods and variables.
  // See https://www.keycloak.org/docs/latest/securing_apps/index.html#javascript-adapter-reference

  return (
    <div>
      <div>{`User is ${
        !keycloak.authenticated ? 'NOT ' : ''
      }authenticated`}</div>

      {!!keycloak.authenticated && (
        <button type="button" onClick={() => keycloak.logout()}>
          Logout
        </button>
      )}
    </div>
  )
}

External Usage (Advanced)

If you need to access keycloak instance from non-React files (such as sagas, utils, providers ...), you can import the instance directly from the keycloak.js file.

The instance will be initialized by react-keycloak but you'll need to be carefull when using the instance and avoid setting/overriding any props, you can however freely access the exposed methods (such as refreshToken, login, etc...).

Examples

Using the privates routes

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { RequireAuth } from '@tabui/react-security';

const App = () => {
  return (  
    <Router>      
        <Suspense fallback={loading}>
        <Routes>
            <Route path="*" element={<DefaultLayout />} />
            <Route path="/private/*" element={
            <RequireAuth roles={['uma_authorization']}>
                <DefaultLayout />
            </RequireAuth>
            } />
        </Routes>      
        </Suspense>
    </Router>
  );
}

Package Sidebar

Install

npm i @tabui/react-security

Weekly Downloads

0

Version

1.0.3

License

ISC

Unpacked Size

559 kB

Total Files

20

Last publish

Collaborators

  • abidesa