Skip to content

A set of react components to make Oidc (Open ID Connect) client easy. It aim to simplify OAuth authentication between multiples providers. Compatible with NextJS.

License

Notifications You must be signed in to change notification settings

zyofeng/react-oidc

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@axa-fr/react-oidc

React Oidc CI Quality Gate Reliability Security Code Corevage Twitter

Try the demo at https://black-rock-0dc6b0d03.1.azurestaticapps.net/

Sample React Oicd

A set of react components to make Oidc (OpenID Connect) client easy. It aim to simplify OAuth authentication between multiples providers. It is compatible with NextJS.

About

These libraries is used to manage client authentication.

  • Secure :
    • With the use of Service Worker, your tokens (refresh_token and access_token) are not accessible to the javascript client code (big protection against XSRF attacks)
    • OIDC using client side Code Credential Grant with pkce only
  • Lightweight
  • Simple :
    • refresh_token and access_token are auto refreshed in background
    • with the use of the Service Worker, you do not need to inject the access_token in every fetch, you have only to configure OidcTrustedDomains.js file
  • No cookies problem : You can disable silent signin (that internally use an iframe). For your information, your OIDC server should be in the same domain of your website in order to be able to send OIDC server cookies from your website via an internal IFRAME, else, you may encounter COOKIES problem.
  • Multiple Authentication :
    • You can authenticate many times to the same provider with different scope (for example you can acquire a new 'payment' scope for a payment)
    • You can authenticate to multiple different providers inside the same SPA (single page application) website
  • Flexible :
    • Work with Service Worker (more secure) and without for older browser (less secure)

Schema Authorization Code Grant with pcke flow on the using service worker
The service worker catch access_token and refresh_token that will never be accessible to the client.

Work perfectly well with :

Getting Started

Getting Started React using create-react-app

npm install @axa-fr/react-oidc --save

# If you have a "public" folder, the 2 files will be created :
# ./public/OidcServiceWorker.js <-- will be updated at each "npm install"
# ./public/OidcTrustedDomains.js <-- won't be updated if already exist

If you need a very secure mode where refresh_token and access_token will be hide behind a service worker that will proxify requests. The only file you should edit is "OidcTrustedDomains.js".

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { OidcProvider } from '@axa-fr/react-oidc';
import Header from './Layout/Header';
import Routes from './Router';

// This configuration use the ServiceWorker mode only
// "access_token" will be provided automaticaly to the urls and domains configured inside "OidcTrustedDomains.js"
const configuration = {
  client_id: 'interactive.public.short',
  redirect_uri: window.location.origin + '/authentication/callback',
  silent_redirect_uri: window.location.origin + '/authentication/silent-callback', // Optional activate silent-signin that use cookies between OIDC server and client javascript to restore the session
  scope: 'openid profile email api offline_access',
  authority: 'https://demo.duendesoftware.com',
  service_worker_relative_url:'/OidcServiceWorker.js',
  service_worker_only:true,
};

const App = () => (
    <OidcProvider configuration={configuration} >
      <Router>
        <Header />
        <Routes />
      </Router>
    </OidcProvider>
);

render(<App />, document.getElementById('root'));
// OidcTrustedDomains.js

// Add bellow trusted domains, access tokens will automatically injected to be send to
// trusted domain can also be a path like https://www.myapi.com/users, 
// then all subroute like https://www.myapi.com/useers/1 will be authorized to send access_token to.

// Domains used by OIDC server must be also declared here
const trustedDomains = {
  default:["https://demo.duendesoftware.com", "https://www.myapi.com/users"]
};

How to consume

"useOidc" returns all props from the Hook :

import React from 'react';
import {useOidc} from "./oidc";

export const Home = () => {

    const { login, logout, isAuthenticated} = useOidc();
    
    return (
        <div className="container-fluid mt-3">
            <div className="card">
                <div className="card-body">
                    <h5 className="card-title">Welcome !!!</h5>
                    <p className="card-text">React Demo Application protected by OpenId Connect</p>
                    {!isAuthenticated && <button type="button" className="btn btn-primary" onClick={() => login('/profile')}>Login</button>}
                    {isAuthenticated && <button type="button" className="btn btn-primary" onClick={() => logout()}>logout</button>}
                </div>
            </div>
        </div>
    )
};

The Hook method exposes :

  • isAuthenticated : if the user is logged in or not
  • logout: logout function (return a promise)
  • login: login function 'return a promise'

"OidcSecure" component trigger authentication in case user is not authenticated. So, the children of that component can be accessible only once you are connected.

import React from 'react';
import { OidcSecure } from '@axa-fr/react-oidc';

const AdminSecure = () => (
  <OidcSecure>
    <h1>My sub component</h1>}
  </OidcSecure>
);

export default AdminSecure;

How to get IDToken

import { useOidcIdToken } from '@axa-fr/react-oidc';

const DisplayIdToken =() => {
    const{ idToken, idTokenPayload } = useOidcIdToken();

    if(!idToken){
        return <p>you are not authentified</p>
    }
    
    return (
        <div className="card text-white bg-info mb-3">
            <div className="card-body">
                <h5 className="card-title">ID Token</h5>
                {<p className="card-text">{JSON.stringify(idToken)}</p>}
                {idTokenPayload != null && <p className="card-text">{JSON.stringify(idTokenPayload)}</p>}
            </div>
        </div>
    );
}

How to get User Information

import {useOidcUser} from '@axa-fr/react-oidc';

const DisplayUserInfo = () => {
  const {oidcUser, oidcUserLoadingState} = useOidcUser();

  switch (oidcUserLoadingState) {
    case OidcUserStatus.Loading:
      return <p>User Information are loading</p>;
    case OidcUserStatus.Unauthenticated:
      return <p>you are not authenticated</p>;
    case OidcUserStatus.LoadingError:
      return <p>Fail to load user information</p>;
    default:
      return (
              <div className="card text-white bg-success mb-3">
                <div className="card-body">
                  <h5 className="card-title">User information</h5>
                  <p className="card-text">{JSON.stringify(oidcUser)}</p>
                </div>
              </div>
      );
  }
};

More documentation :

Getting Started Vanilla

More documentation :

Run The Demo

git clone https://github.com/AxaGuilDEv/react-oidc.git
cd react-oidc/packages/react
npm install
npm start
# then navigate to http://localhost:4200

Run The NextJS Demo

git clone https://github.com/AxaGuilDEv/react-oidc.git
cd react-oidc/packages/nextjs-demo
npm install
npm run dev
# then navigate to http://localhost:3001

How It Works

These components encapsulate the use of "AppAuth-JS" in order to hide workflow complexity. Internally, native History API is used to be router library agnostic.

More information about OIDC

Migrations

V4 is a complete rewrite. It uses the libraries "App-AuthJS" instead of oidc-client. In the v4 we have chosen to remove a lot the surface API in order to simplify usage and enforce security. In this version you can use a ServiceWorker that will hide the refresh_token and access_token (more secure).

Contribute

About

A set of react components to make Oidc (Open ID Connect) client easy. It aim to simplify OAuth authentication between multiples providers. Compatible with NextJS.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 80.9%
  • JavaScript 17.2%
  • Other 1.9%