Skip to content

Repository files navigation

react-oidc-context

Stable ReleaseCICodecov

Lightweight auth library using the oidc-client-ts library for React single page applications (SPA). Support for hooks and higher-order components (HOC).

Table of Contents

Documentation

This library implements an auth context provider by making use of the oidc-client-ts library. Its configuration is tight coupled to that library.

The User and UserManager is hold in this context, which is accessible from the React application. Additionally it intercepts the auth redirects by looking at the query/fragment parameters and acts accordingly. You still need to setup a redirect uri, which must point to your application, but you do not need to create that route.

To renew the access token, the automatic silent renew feature of oidc-client-ts can be used.

Installation

Using npm

npm install oidc-client-ts react-oidc-context --save

Using yarn

yarn add oidc-client-ts react-oidc-context

Getting Started

Configure the library by wrapping your application in AuthProvider:

// src/index.jsximportReactfrom"react";importReactDOMfrom"react-dom";import{AuthProvider}from"react-oidc-context";importAppfrom"./App";constoidcConfig={authority: "<your authority>",client_id: "<your client id>",redirect_uri: "<your redirect uri>",// ...};ReactDOM.render(<AuthProvider{...oidcConfig}><App/></AuthProvider>,document.getElementById("app"));

Use the useAuth hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (signinRedirect, removeUser and signOutRedirect):

// src/App.jsximportReactfrom"react";import{useAuth}from"react-oidc-context";functionApp(){constauth=useAuth();switch(auth.activeNavigator){case"signinSilent":
return<div>Signing you in...</div>;case"signoutRedirect":
return<div>Signing you out...</div>;}if(auth.isLoading){return<div>Loading...</div>;}if(auth.error){return<div>Oops... {auth.error.message}</div>;}if(auth.isAuthenticated){return(<div>
Hello {auth.user?.profile.sub}{" "}<buttononClick={()=>voidauth.removeUser()}>Log out</button></div>);}return<buttononClick={()=>voidauth.signinRedirect()}>Log in</button>;}exportdefaultApp;

You must provide an implementation of onSigninCallback to oidcConfig to remove the payload from the URL upon successful login. Otherwise if you refresh the page and the payload is still there, signinSilent - which handles renewing your token - won't work.

A working implementation is already in the code here.

Use with a Class Component

Use the withAuth higher-order component to add the auth property to class components:

// src/Profile.jsximportReactfrom"react";import{withAuth}from"react-oidc-context";classProfileextendsReact.Component{render(){// `this.props.auth` has all the same properties as the `useAuth` hookconstauth=this.props.auth;return<div>Hello {auth.user?.profile.sub}</div>;}}exportdefaultwithAuth(Profile);

Call a protected API

As a child of AuthProvider with a user containing an access token:

// src/Posts.jsximportReactfrom"react";import{useAuth}from"react-oidc-context";constPosts=()=>{constauth=useAuth();const[posts,setPosts]=React.useState(Array);React.useEffect(()=>{(async()=>{try{consttoken=auth.user?.access_token;constresponse=awaitfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});setPosts(awaitresponse.json());}catch(e){console.error(e);}})();},[auth]);if(!posts.length){return<div>Loading...</div>;}return(<ul>{posts.map((post,index)=>{return<likey={index}>{post}</li>;})}</ul>);};exportdefaultPosts;

As not a child of AuthProvider (e.g. redux slice) when using local storage (WebStorageStateStore) for the user containing an access token:

// src/slice.jsimport{User}from"oidc-client-ts"functiongetUser(){constoidcStorage=localStorage.getItem(`oidc.user:<your authority>:<your client id>`)if(!oidcStorage){returnnull;}returnUser.fromStorageString(oidcStorage);}exportconstgetPosts=createAsyncThunk("store/getPosts",async()=>{constuser=getUser();consttoken=user?.access_token;returnfetch("https://api.example.com/posts",{headers: {Authorization: `Bearer ${token}`,},});},// ...)

Protect a route

Secure a route component by using the withAuthenticationRequired higher-order component. If a user attempts to access this route without authentication, they will be redirected to the login page.

importReactfrom'react';import{withAuthenticationRequired}from"react-oidc-context";constPrivateRoute=()=>(<div>Private</div>);exportdefaultwithAuthenticationRequired(PrivateRoute,{onRedirecting: ()=>(<div>Redirecting to the login page...</div>)});

Adding event listeners

The underlying UserManagerEvents instance can be imperatively managed with the useAuth hook.

// src/App.jsximportReactfrom"react";import{useAuth}from"react-oidc-context";functionApp(){constauth=useAuth();React.useEffect(()=>{// the `return` is important - addAccessTokenExpiring() returns a cleanup functionreturnauth.events.addAccessTokenExpiring(()=>{if(alert("You're about to be signed out due to inactivity. Press continue to stay signed in.")){auth.signinSilent();}})},[auth.events,auth.signinSilent]);return<buttononClick={()=>voidauth.signinRedirect()}>Log in</button>;}exportdefaultApp;

Automatic sign-in

Automatically sign-in and silently reestablish your previous session, if you close the tab and reopen the application.

// index.jsxconstoidcConfig: AuthProviderProps={
...
userStore: newWebStorageStateStore({store: window.localStorage}),};
// src/App.jsximportReactfrom"react";import{useAuth,hasAuthParams}from"react-oidc-context";functionApp(){constauth=useAuth();const[hasTriedSignin,setHasTriedSignin]=React.useState(false);// automatically sign-inReact.useEffect(()=>{if(!hasAuthParams()&&!auth.isAuthenticated&&!auth.activeNavigator&&!auth.isLoading&&!hasTriedSignin){auth.signinRedirect();setHasTriedSignin(true);}},[auth,hasTriedSignin]);if(auth.isLoading){return<div>Signing you in/out...</div>;}if(!auth.isAuthenticated){return<div>Unable to log in</div>;}return<buttononClick={()=>voidauth.removeUser()}>Log out</button>;}exportdefaultApp;

Contributing

We appreciate feedback and contribution to this repo!

Influences

This library is inspired by oidc-react, which lacks error handling and auth0-react, which is focused on auth0.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

Lightweight auth library based on oidc-client-ts for React single page applications (SPA). Support for hooks and higher-order components (HOC).

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages