Git Product home page Git Product logo

react-auth-wrapper's Introduction

react-auth-wrapper

Stable Release

Lightweight auth library using the react-oidc-context 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 and react-oidc-context libraries. 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 @cognite/react-auth-wrapper --save

Getting Started

Configure the library by wrapping your application in ReactCogniteAuthProvider:

// src/index.jsx
import React from "react";
import ReactDOM from "react-dom";
import { ReactCogniteAuthProvider } from "@cognite/react-auth-wrapper";
import App from "./App";

const oidcConfig = {
  authority: "<your authority>",
  client_id: "<your client id>",
  redirect_uri: "<your redirect uri>",
  // ...
};

ReactDOM.render(
  <ReactCogniteAuthProvider {...oidcConfig}>
    <App />
  </ReactCogniteAuthProvider>,
  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 { useCogAuth } from "@cognite/react-auth-wrapper";

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

  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}{" "}
        <button onClick={() => void auth.removeUser()}>Log out</button>
      </div>
    );
  }

  return <button onClick={() => void auth.signinPopup()}>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.

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-wrapper";

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 "@cognite/react-auth-wrapper";

const Posts = () => {
  const auth = useCogAuth();
  const [posts, setPosts] = useState(null);

  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) {
    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}`,
      },
    });
  }
  // ...
);

Adding event listeners

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

// src/App.jsx
import React from "react";
import { useCogAuth } from "@cognite/react-auth-wrapper";

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

  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;

Contributing

We appreciate feedback and contribution to this repo!

License

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

react-auth-wrapper's People

Contributors

davidlky avatar harish0489-cognite avatar cognite-ornellas avatar

Stargazers

Cole Howard avatar

Watchers

Peter Nicolai Motzfeldt avatar Louis Salin avatar Vegard Økland avatar Ermias avatar Robert Collins avatar Trygve Andre Tønnesland avatar James Cloos avatar Emil Sandstø avatar Aleksandrs Livincovs avatar Nakarin Phooripoom avatar Ilya petin avatar Wim Notredame avatar Øystein Hagen Pettersen avatar Sergei avatar Eirik L. Vullum avatar Daniel Priori avatar  avatar  avatar Nils Barlaug avatar Vibha Srinivasan avatar Johan avatar Robert Lombardo avatar Jacek Lakomiec avatar Alireza Kandeh avatar Rogerio Saboia Júnior avatar Udeshika Sewwandi avatar Per Magne Florvaag avatar QuocViet Le avatar Priyanka Perera avatar Cecilie Uppard avatar Shehan Neomal Mark Fonseka avatar Shashan avatar  avatar

react-auth-wrapper's Issues

react-scripts dependency

This dependency introduces a vulnerability into our code base:
image
Perhaps it could be removed all together, or does the auth-provider need it to run?

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.