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-pkce

v0.9.11

Published

React components to authenticate via PKCE

Downloads

19

Readme

What is It?

This zero-dependency package enables React applications to use an OAuth2 provider for authentication. The OAuth2 provider must support the PKCE Spec.

(TODO: Links to resources that explain why this is a good idea / better than using the implicit flow.)

Check the live demo (source). When prompted to login, you can signup with email (use link at the bottom of the form).

Prerequisites

  • The provider url, e.g. https://login.u5auth.com
  • OAuth2 client credentials (client id and secret), where the client is allowed to use the Authorization code grant.
  • A React application, which is supposed to be secured via OAuth2 (or rather, needs an access_token to authenticate e.g. calls to APIs).

How

Install

npm i react-pkce

Use

First, create an auth context (and related things):

const clientId = "8cb4904ae5581ecc2b3a1774"
const clientSecret = "b683283462070edbac15a8fdab751ada0f501ab48a5f06aa20aee3be24eac9cc"
const provider = "https://authenticate.u5auth.com"

const {AuthContext, Authenticated, useToken} = createAuthContext({
  clientId,
  clientSecret, // optional, only specify if provider requires it
  provider,
  scopes: [ 'profile', 'otherScope' ]
})

You probably need those in other files, so you may want to export them:

export { AuthContext, Authenticated, useToken }

Next, use the AuthContext to wrap anything that may require an authenticated user / an access token for an authenticated user. Typically, you would wrap the whole app inside of an AuthContext:

function App() {
  return (
    <AuthContext>
      // ... all my other components, e.g. router, pages, etc.
    </AuthContext>
  )
}

Thirdly, when implementing a component that requires an authenticated user, wrap anything you want to protect from the public in an Authenticated component. This will ensure the user gets authanticated, before anything wrapped by Authenticated gets mounted / rendered:

function ProtectedComponent() {
  return (
    <Authenticated>
      <ProtectedComponent />
    </Authenticated>
  )
}

Lastly, if you require the access token, you can use the useToken() hook:

function ComponentWithToken() {
  const { access_token } = useToken()
  const [data, setData] = useState(null)
  useEffect(() => {
    if (!data) {
      fetchData({ token: access_token }).then(setData)
    }
  }, [access_token])
  return (
    // render the data (or a loading indicator, while data === null)
  )
}

Note: You need to provide your own fetchData() function.

Options

In addition to the required properties (clientId etc), the following properties can be specified when calling createAuthContext():

  • busyIndicator: A React element to be rendered while logging in, e.g. <Spinner />.
  • fetch: HTTP requests to talk to the OAuth2 provider are done using window.fetch, unless you specify your own fetch function as a property.
  • storage: By default, authentication information (the token) is kept in window.sessionStorage. If you want to use different storage (e.g. window.localStorage), set this property. (TODO: won't work yet, as we don't check expiry of tokens!)
  • tokenEndpoint: The default token endpoint is ${provider}/token. Configure a different token endpoint here, if your OAuth2 provider does not follow this convention.

Example

Check the live demo (see above), also checkout the test app.

You can run the example, after cloning the repo, and:

npm i
npm run start

... then connect to http://localhost:3001.

Develop

Run the example, see above. As the example runs via react-scripts, you can live-edit the sample, and the code of this package, which lives under ./src/lib.

Status

It's fully functional, but does not deal with token expiry and/or certain error conditions yet. See the issues and/or add a new issue.