All Projects → sandrinodimattia → Use Auth0 Hooks

sandrinodimattia / Use Auth0 Hooks

Licence: mit
An easy way to sign in with Auth0 in your React application (client-side) using React Hooks

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Use Auth0 Hooks

Material Kit React
React Dashboard made with Material UI’s components. Our pro template contains features like TypeScript version, authentication system with Firebase and Auth0 plus many other
Stars: ✭ 3,465 (+4342.31%)
Mutual labels:  auth0
Auth0.js
Auth0 headless browser sdk
Stars: ✭ 755 (+867.95%)
Mutual labels:  auth0
Auth0 Socketio Jwt
Authenticate socket.io incoming connections with JWTs
Stars: ✭ 1,093 (+1301.28%)
Mutual labels:  auth0
Graphcool Templates
📗 Collection of Graphcool Templates
Stars: ✭ 354 (+353.85%)
Mutual labels:  auth0
Auth0 React Samples
Auth0 Integration Samples for React Applications
Stars: ✭ 672 (+761.54%)
Mutual labels:  auth0
Vue Auth0 Demo
Supporting resource for the article: Managing User Session And Refreshing Auth0 Tokens In a Vuejs Application (https://medium.com/@giza182/managing-user-session-and-refreshing-auth0-tokens-in-a-vuejs-application-65eb29c309bc. Shows how to manage and refresh auth0 tokens unobtrusively and without using a refresh token. Demo: http://bit.ly/2HFOrIo
Stars: ✭ 20 (-74.36%)
Mutual labels:  auth0
auth0-jquery-samples
Auth0 Integration Samples for jQuery
Stars: ✭ 14 (-82.05%)
Mutual labels:  auth0
Auth0 Express Api Samples
Auth0 Integration Samples for Node Express REST API Services
Stars: ✭ 68 (-12.82%)
Mutual labels:  auth0
Nextjs Auth0
Next.js SDK for signing in with Auth0
Stars: ✭ 690 (+784.62%)
Mutual labels:  auth0
Ember Simple Auth Auth0
Auth0 + lock.js, built on ember-simple-auth
Stars: ✭ 53 (-32.05%)
Mutual labels:  auth0
Samlify
🔐 Node.js API for Single Sign On (SAML 2.0)
Stars: ✭ 413 (+429.49%)
Mutual labels:  auth0
Pizzaql
🍕 Modern OSS Order Management System for Pizza Restaurants
Stars: ✭ 631 (+708.97%)
Mutual labels:  auth0
Findme
serverless application to find unlabelled photos of you on twitter using machine learning (tensorflow.js).
Stars: ✭ 43 (-44.87%)
Mutual labels:  auth0
Springy Store Microservices
Springy Store is a conceptual simple μServices-based project using the latest cutting-edge technologies, to demonstrate how the Store services are created to be a cloud-native and 12-factor app agnostic. Those μServices are developed based on Spring Boot & Cloud framework that implements cloud-native intuitive, design patterns, and best practices.
Stars: ✭ 318 (+307.69%)
Mutual labels:  auth0
Miniflix
Miniflix - A smaller version of Netflix powered by Cloudinary
Stars: ✭ 58 (-25.64%)
Mutual labels:  auth0
django-auth0
Auth0 authentication backend for awesome Django apps
Stars: ✭ 57 (-26.92%)
Mutual labels:  auth0
Keystonejs Auth
A Secure Star Wars API developed with KeystoneJS
Stars: ✭ 13 (-83.33%)
Mutual labels:  auth0
Auth0 Python Api Samples
Auth0 Integration Samples for Python REST API Services using Flask
Stars: ✭ 70 (-10.26%)
Mutual labels:  auth0
Nextjs Auth0 Hasura
Template project for Nextjs + Auth0 + Hasura with Apollo.
Stars: ✭ 59 (-24.36%)
Mutual labels:  auth0
Docker Swarm Cookbook
A large collection of recipes for a complete, self-hosted Docker Swarm stack including Traefik v2 and SSO/Auth
Stars: ✭ 49 (-37.18%)
Mutual labels:  auth0

This repository has been archived! Auth0's official React SDK is now available here: https://github.com/auth0/auth0-react

use-auth0-hooks

An easy way to sign in with Auth0 in your React application (client-side) using React Hooks.

Highlights:

  • Support hooks and class based components
  • Pluggable architecture where you can add your error handlers and take action when redirecting
  • Sign in
  • Sign out
  • Request access tokens for your APIs, with automated handling of expired tokens.
  • Require the user to be signed in or make it optional, depending on the page you're on.
  • Built with TypeScript
  • Makes use of @auth0/auth0-spa-js which uses the Authorization Code grant with PKCE (instead of Implicit)

Installation

Using npm:

npm install use-auth0-hooks

Using yarn:

yarn add use-auth0-hooks

Getting Started

Next.js

A full example for Next.js can be found here.

Wrap your application with the Auth0Provider (under /pages/_app.js):

// Create a page which wraps the Auth0 provider.

import { Auth0Provider } from 'use-auth0-hooks';

export default ({ Component, pageProps }) => (
 <Auth0Provider
  domain="sandrino-dev.auth0.com"
  clientId="9f6ClmBt37ZGCXNqToPbefKmzVBSOLa2"
  redirectUri="http://localhost:3000"
 >
  <Component {...pageProps} />
 </Auth0Provider>
)

You can then create a NavBar component with the necessary buttons:

import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router'

import { useAuth } from 'use-auth0-hooks';

export default function NavBar() {
  const { pathname, query } = useRouter();
  const { isAuthenticated, isLoading, login, logout } = useAuth();

  return (
    <header>
      <nav>
        <ul>
          <li>
            <Link href='/'>
              <a>Home</a>
            </Link>
          </li>
          <li>
            <Link href='/about'>
              <a>About</a>
            </Link>
          </li>
          {!isLoading && (
            isAuthenticated ? (
              <>
                <li>
                  <Link href='/profile'>
                    <a>Profile</a>
                  </Link>
                </li>
                <li>
                  <button onClick={() => logout({ returnTo: 'http://localhost:3000' })}>Log out</button>
                </li>
              </>
            ) : (
              <li>
                <button onClick={() => login({ appState: { returnTo: { pathname, query } } })}>
                  Log in
                </button>
              </li>
            )
          )}
        </ul>
      </nav>

      ...
    </header>
  );
};

And finally you can create pages which require authentication:

import React from 'react';

import { withAuth, withLoginRequired } from 'use-auth0-hooks';

function Profile({ auth }) {
  const { user } = auth;
  return (
    <div>
      <h1>Profile</h1>
      <p>This is the profile page.</p>
      <pre>{JSON.stringify(user || { }, null, 2)}</pre>
    </div>
  );
}

export default withLoginRequired(
  withAuth(Profile)
);

Advanced Use Cases

Calling an API

You can use hooks or high order components to get an access token for your API:

import { useAuth, useAccessToken } from 'use-auth0-hooks';

export function SomePage() {
  const { accessToken } = useAuth({
    audience: 'https://api.mycompany.com/',
    scope: 'read:things'
  });

  const { response, isLoading } = callMyApi(`https://localhost/api/my/shows`, accessToken);
  if (isLoading) {
    return (
      <div>Loading your subscriptions ...</div>
    );
  }

  return (
    <div>API call response: {response}</div>
  );
}

Or you can also use it in class based components:

import { Component } from 'react';
import fetch from 'isomorphic-unfetch';

import { withAuth } from 'use-auth0-hooks';

class MyTvShows extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myShows: null,
      myShowsError: null
    };
  }

  async fetchUserData() {
    const { myShows, myShowsError } = this.state;
    if (myShows || myShowsError) {
      return;
    }

    const { accessToken } = this.props.auth;
    if (!accessToken) {
      return;
    }

    const res = await fetch(`${process.env.API_BASE_URL}/api/my/shows`, {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });

    if (res.status >= 400) {
      this.setState({
        myShowsError: res.statusText || await res.json()
      })
    } else {
      const { shows } = await res.json();
      this.setState({
        myShows: shows.map(entry => entry.show)
      })
    }
  }

  async componentDidMount () {
    await this.fetchUserData();
  }

  async componentDidUpdate() {
    await this.fetchUserData();
  }

  render() {
    const { auth } = this.props;
    const { myShows, myShowsError } = this.state;
    return (
      <div>
        {
          myShows && (
            <div>
              <h1>My Favourite TV Shows ({auth.user.email})</h1>
              <p>This is rendered on the client side.</p>
              {myShowsError && <pre>Error loading my shows: {myShowsError}</pre>}
              <ul>
                {state.myShows && state.myShows.map(show => (
                  <li key={show.id}>
                    {show.name}
                  </li>
                ))}
              </ul>
            </div>
          )
        }
      </div>
    );
  }
};

export default withAuth(MyTvShows, {
  audience: 'https://api/tv-shows',
  scope: 'read:shows'
});

Deep Links

When a user clicks the login button on a specific page you'll probably want to send them back to that page after the login is complete. In order to do this you'll want to store the current URL in the application state:

const { pathname, query } = useRouter();
const { login } = useAuth();

return (
  <button onClick={() => login({ appState: { returnTo: { pathname, query } } })}>
    Log in
  </button>
);

And then you'll just provide a method which will be called after the login completed (ie: to redirect the user back to the page they were one):

import App from 'next/app';
import Router from 'next/router';

import Layout from '../components/layout';
import { Auth0Provider } from '../components/auth';

/**
 * Where to send the user after they have signed in.
 */
const onRedirectCallback = appState => {
  if (appState && appState.returnTo) {
    Router.push({
      pathname: appState.returnTo.pathname,
      query: appState.returnTo.query
    })
  }
};

/**
 * Create a page which wraps the Auth0 provider.
 */
export default class Root extends App {
  render () {
    const { Component, pageProps } = this.props;
    return (
      <Auth0Provider
        ...
        onRedirectCallback={onRedirectCallback}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
      </Auth0Provider>
    );
  }
}

Before Login

When redirecting to the login page you'll end up in a state where the login page is still loading and the current page is still showing. You can render a message to explain that the user is being redirected.

/**
 * When redirecting to the login page you'll end up in this state where the login page is still loading.
 * You can render a message to show that the user is being redirected.
 */
const onRedirecting = () => {
  return (
    <div>
      <h1>Signing you in</h1>
      <p>
        In order to access this page you will need to sign in.
        Please wait while we redirect you to the login page...
      </p>
    </div>
  );
};

/**
 * Create a page which wraps the Auth0 provider.
 */
export default class Root extends App {
  render () {
    const { Component, pageProps } = this.props;
    return (
      <Auth0Provider
        ...
        onRedirecting={onRedirecting}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
      </Auth0Provider>
    );
  }
}

Error Handling

If for some reason the login fails (eg: an Auth0 Rule returns an error), you'll want to handle this in your application. One way to do this is to redirect to an error page:

/**
 * When signing in fails for some reason, we want to show it here.
 * @param {Error} err
 */
const onLoginError = (err) => {
  Router.push({
    pathname: '/oops',
    query: {
      message: err.error_description || err.message
    }
  })
};

/**
 * Create a page which wraps the Auth0 provider.
 */
export default class Root extends App {
  render () {
    const { Component, pageProps } = this.props;
    return (
      <Auth0Provider
        ...
        onLoginError={onLoginError}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
      </Auth0Provider>
    );
  }
}

You can also be notified when retrieving an new access token is not possible:

const onAccessTokenError = (err, options) => {
  console.error('Failed to retrieve access token: ', err);
};

/**
 * Create a page which wraps the Auth0 provider.
 */
export default class Root extends App {
  render () {
    const { Component, pageProps } = this.props;
    return (
      <Auth0Provider
        ...
        onAccessTokenError={onAccessTokenError}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
      </Auth0Provider>
    );
  }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].