Giter Club home page Giter Club logo

react-oidc's Introduction

React OIDC

A few opinionated React components wrapping oidc-client using the Hooks API.

npm install @connelhooley/react-oidc

To use this plugin, the oidc server you are interacting with must supply the following additional claims:

  • name
  • email
  • role

AuthProvider

All other components in this library must be placed inside a single AuthProvider component. Place this component as close to your root component as possible but under a BrowserRouter. The AuthProvider component handles sign-in callback routes. All other routes should be handled by its children. It also sets up the user context so information about the logged in user can be accessed by its children, see useUser for more information.

export function App() {
    const oidcSettings = {
        authority: "https://example-authority.com",
        client_id: "example-client-id",
        response_type: "code",
        response_mode: "query",
        scope: "openid profile another-example-scope",
        redirect_uri: "https://this-app.com/callback",
        silent_redirect_uri: "https://this-app.com/silent-callback",
        post_logout_redirect_uri: "https://this-app.com/",
        clockSkew: 60,
        automaticSilentRenew: true,
        accessTokenExpiringNotificationTime: 0,
    };
    return (
        <BrowserRouter>
            <AuthProvider
                oidcSettings={oidcSettings}
                signInCallbackRoute="/callback"
                silentSignInCallbackRoute="/silent-callback"
                signInCallbackFallbackRoute="/"
                defaultAuthorizedRouteRedirect="/"
                defaultNotAuthorizedRouteRedirect="/"
                loadingComponentFactory= {() => <Loading />}>
                    <Switch>
                        <Route exact path="/">
                            <HomePage />
                        </Route>
                    </Switch>
            </AuthProvider>
        </BrowserRouter>
    );
}
  • The oidcSettings prop is the config class sent to the oidc-client library.
  • The signInCallbackRoute prop is the route that completes the sign in process when the user is redirected back to the application. It must match up with the redirect_uri property in the oidcSettings prop. Defaults to "/callback".
  • The silentSignInCallbackRoute prop is the route that refreshes the user token in the background via an iframe. It must match up with the silent_redirect_uri property in the oidcSettings prop. Defaults to "/silent-callback".
  • The signInCallbackFallbackRoute prop is the route the user is redirected to if an error occurs finding the return URL in state. Defaults to "/".
  • The defaultAuthorizedRouteRedirect prop is the route the user is redirected to, when they try an access an "authorized" route and they are not signed in. See AuthorizedRoute for more information. Defaults to "/".
  • The defaultNotAuthorizedRouteRedirect prop is the route the user is redirected to, when they try an access a "not authorized" route and they are signed in. See NotAuthorizedRoute for more information. Defaults to "/".
  • The loadingComponentFactory prop is a function that returns the component to be rendered when the user is completing the sign in process. This is optional, if it is not provided no element is rendered.

useUser

Returns information about the signed in user. The returned object can be either:

  • An object containing information about the user when the user is signed in.
  • false when the user is not signed in.
  • undefined when the user is signing in.
export function HomePage() {
    const user = useUser();
    if (user) {
        return (
            <h1>Signed in</h1>
            <p>{user.id}</p>
            <p>{user.name}</p>
            <p>{user.email}</p>
            <p>{user.role}</p>
            <p>{user.accessToken}</p>
        );
    } else if (user == false) {
        return (
            <h1>Not signed in</h1>
        );
    } else {
        return (
            <h1>Signing in</h1>
        );
    }
}

useAccessToken

Returns the access token for the signed in user if available. The returned object can be either:

  • A string containing the access token when the user is signed in.
  • undefined when the user is signing in or is not signed in.
export function HomePage() {
    const accessToken = useAccessToken();
    if (accessToken) {
        return (
            <h1>Signed in</h1>
            <p>{user.accessToken}</p>
        );
    } else {
        return (
            <h1>Signing in or not signed in</h1>
        );
    }
}

The access token can be used to create Authorization bearer headers in HTTP clients, below is a quick example using fetch:

const accessToken = useAccessToken();
const authHeader = user
    ? { "Authorization": `Bearer ${accessToken}` }
    : undefined;
const res = await fetch("https://example.com", {
    method: "GET",
    headers: {
        "Accept": "application/json",
        ...(authHeader ?? {}),
    },
});

Authorized

Only renders its children if the user is authenticated.

export function Example() {
    return (
        <Authorized>
            <p>The user is signed in</p>
        </Authorized>
    );
}

You can also provide a role and the Authorized component will only render its children if the user is authenticated and has that role.

export function Example() {
    return (
        <Authorized role="admin">
            <p>The user is signed in and is an admin</p>
        </Authorized>
        <Authorized role="customer">
            <p>The user is signed in and is a customer</p>
        </Authorized>
    );
}

NotAuthorized

Only renders its children if the user is not authenticated.

export function Example() {
    return (
        <NotAuthorized>
            <p>The user is not signed in</p>
        </NotAuthorized>
    );
}

You can also provide a role and the NotAuthorized component will render its children if the user is unauthenticated or authenticated with a different role.

export function Example() {
    return (
        <NotAuthorized role="admin">
            <p>The user is either signed out or is signed in but is not an admin</p>
        </NotAuthorized>
        <NotAuthorized role="customer">
            <p>The user is either signed out or is signed in but is not an customer</p>
        </NotAuthorized>
    );
}

Authorizing

Only renders its children if the user is currently signing in.

export function Example() {
    return (
        <Authorizing>
            <p>The user is in the process of signing in</p>
        </Authorizing>
    );
}

AuthorizedRoute

Only renders its children if its route is matched and the user is currently signed in. If the user is not signed in, the component redirects to the defaultAuthorizedRouteRedirect value specified in the parent AuthProviderRouters props.

export function Routes() {
    return (
        <Switch>
            <Route path="/">
                <HomePage />
            </Route>
            <AuthorizedRoute path="/profile">
                <ProfilePage />
            </Route>
        </Switch>
    );
}

You can also provide a redirect value in the AuthorizedRoutes props to configure where the route redirects to if the user is not signed in.

export function Routes() {
    return (
        <Switch>
            <Route path="/">
                <HomePage />
            </Route>
            <AuthorizedRoute path="/profile" redirect="/profile-404">
                <ProfilePage />
            </Route>
            <Route path="/profile-404">
                <ProfileNotFoundPage />
            </Route>
        </Switch>
    );
}

NotAuthorizedRoute

Only renders its children if its route is matched and the user is not currently signed in. If the user is signed in, the component redirects to the defaultNotAuthorizedRouteRedirect value specified in the parent AuthProviderRouters props.

export function Routes() {
    return (
        <Switch>
            <Route path="/">
                <HomePage />
            </Route>
            <NotAuthorizedRoute path="/register">
                <RegistrationPage />
            </Route>
        </Switch>
    );
}

You can also provide a redirect value in the NotAuthorizedRoutes props to configure where the route redirects to if the user is signed in.

export function Routes() {
    return (
        <Switch>
            <Route path="/">
                <HomePage />
            </Route>
            <NotAuthorizedRoute path="/register" redirect="/already-registered">
                <RegistrationPage />
            </Route>
            <Route path="/already-registered">
                <AlreadyRegisteredPage />
            </Route>
        </Switch>
    );
}

SignInButton

Starts sign in process by redirecting the user when clicked.

export function Nav() {
    return (
        <SignInButton>Click here to sign in</SignInButton>
    );
}

All props are passed down to the underlying button meaning the component can be styled using CSS-in-JS libraries such as styled-components.

SignOutButton

Starts sign out process by redirecting the user when clicked.

export function Nav() {
    return (
        <SignOutButton>Click here to sign out</SignOutButton>
    );
}

All props are passed down to the underlying button meaning the component can be styled using CSS-in-JS libraries such as styled-components.

SignIn

Starts the sign in process by redirecting one second after it is rendered.

export function SignInRoute() {
    return (
        <SignIn>Loading...</SignIn>
    );
}

You can also provide a delay value in the SignIns props to configure the duration to delay before starting the signing process:

export function SignInRoute() {
    return (
        <SignIn delay={3000}>Loading for 3 seconds...</SignIn>
    );
}

react-oidc's People

Contributors

connelhooley avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

tostringtheory

react-oidc's Issues

Silent implicit flow failure

I wrote a simple app with your library and I see it authenticating in the developer console.

import React, { useState } from 'react';
import Navbar from 'react-bootstrap/Navbar';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
 
import { Log } from 'oidc-client';
 
import {
  AuthProvider,
  Authorized,
  NotAuthorized,
  SignInButton,
} from '@connelhooley/react-oidc';
 
Log.logger = console;
Log.level = Log.DEBUG;
 
const oidcSettings = {
  authority: '<REMOVED>',
  client_id: '<REMOVED>',
  response_type: 'id_token',
  response_mode: 'query',
  scope: 'openid email',
  redirect_uri: `http://localhost:3000/callback`,
  silent_redirect_uri: `http://localhost:3000/silent-callback`,
  post_logout_redirect_uri: `http://localhost:3000`,
  clockSkew: 60,
  automaticSilentRenew: true,
  accessTokenExpiringNotificationTime: 0,
};
 
function App() {
  return (
    <div>
      <Router>
        <AuthProvider
          oidcSettings={oidcSettings}
          signInCallbackRoute="/callback"
          silentSignInCallbackRoute="/silent-callback"
          signInCallbackFallbackRoute="/"
          defaultAuthorizedRouteRedirect="/"
          defaultNotAuthorizedRouteRedirect="/"
        >
          <Navbar className="mb-4" variant="dark" bg="dark">
            <Authorized>Logged in</Authorized>
            <NotAuthorized>
              <SignInButton>Sign In</SignInButton>
            </NotAuthorized>
          </Navbar>
          <Switch>
            <Route path="/">
              <Authorized>Logged in</Authorized>
              <NotAuthorized>Not Logged in</NotAuthorized>
            </Route>
          </Switch>
        </AuthProvider>
      </Router>
    </div>
  );
}
 
export default App;

In the browser console, I see

UserManager.signinRedirectCallback: successful, signed in sub:  my-username

After I click the SignIn button. I also see all the proper network calls. But I am still seeing "Not Logged in" in the main page.

What might be wrong? How can I debug?

Any guidance on testing components that utilize react-oidc?

@connelhooley - thanks for providing a really useful package that immediately filled some of my needs in my project. Very elegant/clean solution.

My main/major question thus far however, is do you have any guidance on how best to mock/test a component, when there's some dependencies on the react-oidc library? I am using jest with @testing-library/react.

Take for example a component that depends on Authorized, NotAuthorized, and Authorizing. All 3 of these depend on useUser, which then depends on AuthProvider. I'll be honest, my jest mocking skills aren't the greatest, and I can't figure out for the life of me how to best mock being in the context of a user.

The closest I came was to mock the entire library via a jest.mock call, and return a module mock:

jest.mock("@connelhooley/react-oidc", () => ({
	...(jest.requireActual("@connelhooley/react-oidc") as Record<string, unknown>),
	useUser: jest.fn(),
	SignIn: () => (<div>Redirect to Sign In</div>),
	Authorized: ({ children }: { children: React.ReactNode }) => (<>{children}</>),
	Authorizing: ({ children }: { children: React.ReactNode }) => (<>{children}</>),
	NotAuthorized: ({ children }: { children: React.ReactNode }) => (<>{children}</>)
}));

This really however seems like a hack and I feel there's got to be a better way. I figured you might have some idea seeing as how I see you have some tests in this project (I tried to utilize the same strategies to no avail), but figured you may be using this library in something else of yours with some tests too.

Support manual configuration

It looks like you are making requests to /.well-known/openid-configuration. I couldn't find where in your code, but I would like to add support for manually specifying the various endpoints like authorization, token, userinfo, etc. AWS Cognito does not have the .well-known endpoints, so I would need to configure the Cognito endpoints manually.

Can you briefly explain how I could add this support to your library (assuming you are willing to take a PR :) )? I couldn't find references in your code

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.