Coder Social home page Coder Social logo

react-keycloak's Introduction

React Keycloak

React Keycloak

React bindings for Keycloak

License Build Status Coverage Status NPM version

Dependencies Github Issues

Install

React Keycloak requires:

  • React 16.0 or later
  • a version of keycloak-js matching the major version (e.g. "react-keycloak": "6.x.y" => "keycloak-js": "6.z.k")
yarn add react-keycloak

or

npm install --save react-keycloak

Getting Started

Setup KeycloakProvider

Wrap your App inside KeycloakProvider and pass a keycloak instance as prop

import Keycloak from 'keycloak-js';
import { KeycloakProvider } from 'react-keycloak';

// Setup Keycloak instance as needed
const keycloak = new Keycloak();

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

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

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

  • initConfig, 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
    • 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,
    }

HOC Usage

When a component requires access to Keycloak, wrap it inside the withKeycloak HOC.

import { withKeycloak } from 'react-keycloak';

const LoginPage = ({ keycloak, keycloakInitialized }) => {
  // 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>
      <button type="button" onClick={() => keycloak.login()}>
        Login
      </button>
    </div>
  );
};

export default withKeycloak(LoginPage);

Hook Usage (React >=16.8 required)

Alternately, when a component requires access to Keycloak, you can also use the useKeycloak Hook.

import { useKeycloak } from 'react-keycloak';

export default () => {
  // Using array destructuring
  const [keycloak, initialized] = useKeycloak();
  // or 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>
  );
};

Demo

See inside src/demo for a demo implementing this library main features.

To run the demo app:

  • Clone/Download this repo
  • Install dependencies (npm install or yarn)
  • Place a valid keycloak.json file inside public folder or setup Keycloak instance inside src/demo/App.js following Keycloak guide
  • Run the demo (npm start or yarn start)

Note: The demo app is not meant to be production-ready nor a starter-kit but just a way to show this module components and their usage.

Credits

Library bootstrapped using DimiMikadze/create-react-library and inspired by react-redux


Made with ✨ & ❤️ by Mattia Panzeri and contributors

If you found this project to be helpful, please consider buying me a coffee.

buy me a coffee

react-keycloak's People

Contributors

arnabk avatar betheny-carmani avatar kunyan avatar panz3r avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.