react-oidc-context vs oidc-client
OpenID Connect Client Libraries Comparison
1 Year
react-oidc-contextoidc-clientSimilar Packages:
What's OpenID Connect Client Libraries?

These libraries facilitate authentication and authorization in web applications using the OpenID Connect protocol. They help developers manage user sessions, handle tokens, and integrate with identity providers, streamlining the process of implementing secure user authentication in applications. The oidc-client library is a general-purpose JavaScript library for handling OpenID Connect, while react-oidc-context is specifically designed for React applications, providing a context-based approach to manage authentication state and user information.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-oidc-context172,361866113 kB873 months agoMIT
oidc-client148,1362,433-1164 years agoApache-2.0
Feature Comparison: react-oidc-context vs oidc-client

Framework Compatibility

  • react-oidc-context:

    react-oidc-context is specifically tailored for React applications, leveraging React's context API to provide authentication state and methods throughout the component tree. This makes it highly compatible with React's component-based architecture.

  • oidc-client:

    oidc-client is a standalone library that can be used with any JavaScript framework or even vanilla JavaScript. It provides a flexible API for managing OpenID Connect authentication flows, making it suitable for various types of applications beyond just React.

State Management

  • react-oidc-context:

    react-oidc-context simplifies state management by using React's context API. It automatically provides authentication state and methods to any component that needs them, reducing boilerplate code and making it easier to manage user sessions in a React application.

  • oidc-client:

    oidc-client requires manual management of authentication state, which gives developers the flexibility to implement their own state management solutions, but also adds complexity. Developers need to handle token storage, renewal, and session management explicitly.

Ease of Use

  • react-oidc-context:

    react-oidc-context offers a more intuitive and straightforward API for React developers. It abstracts much of the complexity involved in managing authentication, allowing developers to focus on building their applications without getting bogged down in the details of the authentication process.

  • oidc-client:

    oidc-client has a steeper learning curve due to its more generic approach and the need for manual configuration of authentication flows. Developers need to understand the OpenID Connect protocol well to implement it effectively.

Token Management

  • react-oidc-context:

    react-oidc-context automatically handles token management for you, including storage and renewal, which simplifies the implementation process. However, it may offer less flexibility for custom token handling compared to oidc-client.

  • oidc-client:

    oidc-client provides comprehensive support for handling tokens, including access tokens, ID tokens, and refresh tokens. It allows developers to implement custom logic for token storage and renewal, which can be beneficial for advanced use cases.

Community and Support

  • react-oidc-context:

    react-oidc-context, while more niche, is specifically designed for the React community. It benefits from React's ecosystem and has good documentation, but may have fewer community resources compared to the more general oidc-client.

  • oidc-client:

    oidc-client has a broad user base and is widely used across various JavaScript applications. This means there is a wealth of community resources, documentation, and support available for developers.

How to Choose: react-oidc-context vs oidc-client
  • react-oidc-context:

    Choose react-oidc-context if you are developing a React application and prefer a more streamlined approach to managing authentication state. This package provides React hooks and context, making it easier to access authentication information throughout your component tree without the need for prop drilling.

  • oidc-client:

    Choose oidc-client if you need a versatile and framework-agnostic solution that can be integrated into various JavaScript applications, not limited to React. It is suitable for projects where you want to have more control over the authentication flow and manage the state manually.

README for react-oidc-context

react-oidc-context

Stable Release CI Codecov

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.jsx
import React from "react";
import ReactDOM from "react-dom";
import { AuthProvider } from "react-oidc-context";
import App from "./App";

const oidcConfig = {
  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.jsx
import React from "react";
import { useAuth } from "react-oidc-context";

function App() {
    const auth = 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.kind} caused {auth.error.message}</div>;
    }

    if (auth.isAuthenticated) {
        return (
        <div>
            Hello {auth.user?.profile.sub}{" "}
            <button onClick={() => void auth.removeUser()}>Log out</button>
        </div>
        );
    }

    return <button onClick={() => void auth.signinRedirect()}>Log in</button>;
}

export default App;

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.jsx
import React from "react";
import { withAuth } from "react-oidc-context";

class Profile extends React.Component {
    render() {
        // `this.props.auth` has all the same properties as the `useAuth` hook
        const auth = this.props.auth;
        return <div>Hello {auth.user?.profile.sub}</div>;
    }
}

export default withAuth(Profile);

Call a protected API

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

// src/Posts.jsx
import React from "react";
import { useAuth } from "react-oidc-context";

const Posts = () => {
    const auth = useAuth();
    const [posts, setPosts] = React.useState(Array);

    React.useEffect(() => {
        (async () => {
            try {
                const token = auth.user?.access_token;
                const response = await fetch("https://api.example.com/posts", {
                    headers: {
                        Authorization: `Bearer ${token}`,
                    },
                });
                setPosts(await response.json());
            } catch (e) {
                console.error(e);
            }
        })();
    }, [auth]);

    if (!posts.length) {
        return <div>Loading...</div>;
    }

    return (
        <ul>
        {posts.map((post, index) => {
            return <li key={index}>{post}</li>;
        })}
        </ul>
    );
};

export default Posts;

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

// src/slice.js
import { User } from "oidc-client-ts"

function getUser() {
    const oidcStorage = localStorage.getItem(`oidc.user:<your authority>:<your client id>`)
    if (!oidcStorage) {
        return null;
    }

    return User.fromStorageString(oidcStorage);
}

export const getPosts = createAsyncThunk(
    "store/getPosts",
    async () => {
        const user = getUser();
        const token = user?.access_token;
        return fetch("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.

import React from 'react';
import { withAuthenticationRequired } from "react-oidc-context";

const PrivateRoute = () => (<div>Private</div>);

export default withAuthenticationRequired(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.jsx
import React from "react";
import { useAuth } from "react-oidc-context";

function App() {
    const auth = useAuth();

    React.useEffect(() => {
        // the `return` is important - addAccessTokenExpiring() returns a cleanup function
        return auth.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 <button onClick={() => void auth.signinRedirect()}>Log in</button>;
}

export default App;

Automatic sign-in

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

// index.jsx
const oidcConfig: AuthProviderProps = {
    ...
    userStore: new WebStorageStateStore({ store: window.localStorage }),
};
// src/App.jsx
import React from "react";
import { useAuth, hasAuthParams } from "react-oidc-context";

function App() {
    const auth = useAuth();
    const [hasTriedSignin, setHasTriedSignin] = React.useState(false);

    // automatically sign-in
    React.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 <button onClick={() => void auth.removeUser()}>Log out</button>;
}

export default App;

useAutoSignin

Use the useAutoSignin hook inside the AuthProvider to automatically sign in.

// src/App.jsx
import React from "react";
import { useAutoSignin } from "react-oidc-context";

function App() {
    // If you provide no signinMethod at all, the default is signinRedirect
    const { isLoading, isAuthenticated, error } = useAutoSignin({signinMethod: "signinRedirect"});

    if (isLoading) {
        return <div>Signing you in/out...</div>;
    }

    if (!isAuthenticated) {
        return <div>Unable to log in</div>;
    }

    if(error) {
        return <div>An error occured</div>
    }

    return <div>Signed in successfully</div>;
}

export default App;

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.