npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-oidc

v1.0.3

Published

Wrapper for the OIDC JavaScript client, to be used in React projects.

Downloads

11,670

Readme

React OIDC

Wrapper for oidc-client-js, to be used in React apps.

Quick start

You should read the slow start and Routing Considerations too

yarn add react-oidc

You will need the config for the UserManager class.

Example using react-router

import { makeAuthenticator, makeUserManager, Callback } from 'react-oidc'

// supply this yourself
import App from '../layouts/App'
import userManagerConfig from '../config'

const userManager = makeUserManager(userManagerConfig)
const AppWithAuth = makeAuthenticator({
  userManager: userManager,
  signinArgs: {
    state: {
      foo: 15
    }
  }
})(App)

export default () => (
  <Router>
    <Switch>
      <Route
        path="/callback"
        render={routeProps => (
          <Callback
            onSuccess={user => {
              // `user.state` will reflect the state that was passed in via signinArgs.
              routeProps.history.push('/')
            }}
            userManager={userManager}
          />
        )}
      />
      <AppWithAuth />
    </Switch>
  </Router>
)

Slow start

There are 3 main parts to this library:

  • makeUserManager function;
  • makeAuthenticator function;
  • Callback component

makeUserManager(config)

| Param | Type | Required | Default Value | Description | | -------- | ------------------------------ | -------- | ------------- | -------------------------------------- | | config | object (UserManagerSettings) | Yes | undefined | Config object to pass to UserManager |

Helper utility to create a UserManager instance.

makeAuthenticator(params)(<ProtectedApp />)

| Param | Type | Required | Default Value | Description | | ---------------------- | ------------- | -------- | ------------- | ---------------------------------------------------------------- | | userManager | UserManager | Yes | undefined | UserManager instance (the result of makeUserManager()) | | placeholderComponent | Component | No | null | Optional component to render while auth state is being retrieved |

This is a higher-order function that accepts a UserManager instance, and optionally a placeholder component to render when user auth state is being retrieved. It returns a function that accepts a React component. This component should contain all components that you want to be protected by your authentication. Ultimately you will get back a component that either renders the component you passed it (if the user is authenticated), or redirects to the OIDC login screen as defined by the Identity Provider.

The lifecycle of this component is as follows:

  1. The component is constructed with a fetching flag set to true.

  2. On mount, the .getUser() method from UserManager is called. If the user is already authenticated, it will set the fetching flag to false and render the component you passed it.

  3. If the user is not authenticated or their token has expired, the user will be redirected to the login URL (defined by the Identity Provider) and the fetching flag will be set to false.

  4. Upon successful authentication with the Identity Provider, the user will be redirected to the redirect_uri. You should render the Callback component at this location.

Note on the fetching flag

The fetching flag is set to true initially because of the asynchronous nature of .getUser(). There is a need to ensure that we do not redirect to the login page whilst getUser is resolving. Without some way of knowing when the user auth state query is complete, we would end up always redirecting to the login page.

<Callback />

| Prop | Type | Required | Default Value | Description | | ------------- | ------------- | -------- | ------------- | ----------------------------------------------------------------------------------------------- | | userManager | UserManager | Yes | undefined | UserManager instance (the result of makeUserManager()) | | children | Component | No | null | Optional component to render at the redirect page | | onError | function | No | undefined | Optional callback if there is an error from the Promise returned by .signinRedirectCallback() | | onSuccess | function | No | undefined | Optional callback when the Promise from .signinRedirectCallback() resolves |

The Callback component will call the .signinRedirectCallback() method from UserManager and if successful, call the onSuccess prop. On error it will call the onError prop. You should pass the same instance of UserManager that you passed to makeAuthenticator.

<UserData />

This component exposes the data of the authenticated user. If you are familiar with React's Context API (the official v16.3.x one), this component is just a Context.

<UserData.Consumer>
  {context => <p>{context.user.id_token}</p>}
</UserData.Consumer>

Render prop function

| Argument (key of context) | Type | Description | | --------------------------- | ------------- | -------------------------------------------- | | signOut | function | Call this to sign the current user out | | user | User | This is the User object from oidc-client | | userManager | UserManager | UserManager instance from oidc-client |

Routing considerations

This library is deliberately unopinionated about routing, however there are restrictions from the oidc-client library that should be considered.

  1. There will be url redirects. It is highly recommended to use a routing library like react-router to help deal with this.

  2. The redirect_uri should match eagerly. You should not render the result of makeAuthenticator()() at the location of the redirect_uri. If you do, you will end up in a redirect loop that ultimately leads you back to the authentication page. In the quick start above, a Switch from react-router is used, and the Callback component is placed before AppWithAuth. This ensures that when the user is redirected to the redirect_uri, AppWithAuth is not rendered. Once the user data has been loaded into storage, onSuccess is called and the user is redirected back to a protected route. When AppWithAuth loads now, the valid user session is in storage and the protected routes are rendered.