All Projects → qruzz → react-auth-hook

qruzz / react-auth-hook

Licence: other
A small library for authenticating users in React using Auth0.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-auth-hook

Reactjs Authentication Tutorial
Chuck Norris World App - A sample app that shows how to add authentication to a ReactJS app
Stars: ✭ 139 (+595%)
Mutual labels:  auth0
Useauth
The simplest way to add authentication to your React app. Supports various providers.
Stars: ✭ 2,532 (+12560%)
Mutual labels:  auth0
auth0-cli
Build, manage and test your Auth0 integrations from the command line
Stars: ✭ 186 (+830%)
Mutual labels:  auth0
Cfworker
A collection of packages optimized for Cloudflare Workers and service workers.
Stars: ✭ 152 (+660%)
Mutual labels:  auth0
Starter Pack
Combines React (ft. hooks), Redux, Redux-saga and TypeScript with Auth0 as a starting point for modern web apps with solid authentication
Stars: ✭ 209 (+945%)
Mutual labels:  auth0
Actingweb firstapp
Starter app for Flutter that includes many different production app features; some not typically included in demo apps.
Stars: ✭ 224 (+1020%)
Mutual labels:  auth0
Mumuki Laboratory
🔬 Where students practice and receive automated and human feedback
Stars: ✭ 131 (+555%)
Mutual labels:  auth0
restish
Restish is a CLI for interacting with REST-ish HTTP APIs with some nice features built-in
Stars: ✭ 453 (+2165%)
Mutual labels:  auth0
Auth0 Vue Samples
Auth0 Integration Samples for Vue.js Applications
Stars: ✭ 215 (+975%)
Mutual labels:  auth0
Terraform Provider Auth0
Auth0 Terraform Provider
Stars: ✭ 252 (+1160%)
Mutual labels:  auth0
Golang Gin
Build a Golang app with the Gin framework, and authenticate with Auth0 + JWT
Stars: ✭ 160 (+700%)
Mutual labels:  auth0
Prisma Auth0 Example
Boilerplate Prisma Startup
Stars: ✭ 184 (+820%)
Mutual labels:  auth0
Auth0 Angular Samples
Auth0 Integration Samples for Angular 2+ Applications
Stars: ✭ 227 (+1035%)
Mutual labels:  auth0
Auth0.swift
Swift toolkit for Auth0 API
Stars: ✭ 146 (+630%)
Mutual labels:  auth0
auth0-golang-web-app
Auth0 Integration Samples for Go Web Applications
Stars: ✭ 112 (+460%)
Mutual labels:  auth0
Nitro
An Example of a PWA using Nextjs, Material-UI, Typescript and Auth0 💗
Stars: ✭ 130 (+550%)
Mutual labels:  auth0
Lock.swift
A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Stars: ✭ 215 (+975%)
Mutual labels:  auth0
numvalidate
Phone number validation REST API
Stars: ✭ 54 (+170%)
Mutual labels:  auth0
django-mail-auth
Django authentication via login URLs, no passwords required
Stars: ✭ 48 (+140%)
Mutual labels:  auth0
Authing
🔥Authing - IDaaS/IAM solution that can Auth to web and mobile applications.
Stars: ✭ 247 (+1135%)
Mutual labels:  auth0

react-auth-hook

A small library for authenticating users in React using Auth0.



version bundle-size licence

If the library has has helped you, please consider giving it a ⭐️

Table of Content

Getting Started

This module is distributed with npm which is bundled with node and should be installed as one of your projects dependencies:

npm install --save react-auth-hook

or using yarn

yarn add react-auth-hook

This library includes auth0-js as a dependency and requires react as a peerDependency.


You can find a simple example of a react application with typescript in the examples folder in this repository.

Configuring Auth0

react-auth-hook is designed to be quick to setup and easy to use. All it requires is a Auth0 account with a application set up.

There are a few required configurations to be done in your Auth0 application to make react-auth-hook work properly.

Allowed Callback URLs

To route back a user after she is authenticated you need to supply a list of URLs that are considered valid. This means that you should add all the URLs which you be authenticating your users from.

Allowed Web Origins

To allow origins for use with Cross-Origin Authentication you should supply a list of URLs that the authentication request will come from.

Allowed Logout URLs

After logging out your users will need to be redirected back from Auth0. Provide a list of valid URLs that Auth- can redirect them to with the returnTo query parameter.

Usage

To use this library and the useAuth hook, you first need to wrap your application in an AuthProvider component to configure the Auth0 client and share state between components.

1. Configure AuthProvider

In your application, wrap the parts you want to be "hidden" behind your authentication layer in the AuthProvider component. I recommend adding it around your root component in the index.js file (in React).

// src/index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { navigate } from '@reach/router';
import { AuthProvider } from 'react-auth-hook';

ReactDOM.render(
	<AuthProvider
		auth0Domain="reactauthhook.eu.auth0.com"
		auth0ClientId="5iK42vpGXdMDbKvW1Gkz3I8D8352vNWa"
		navigate={navigate}
	>
		<App />
	</AuthProvider>,
	document.getElementById('root')
);

The AuthProvider create the context, sets up an immutable state reducer, and instantiates the Auth0 client.

2. Handle the Callback

Auth0 use OAuth which required you to redirect your users to their login form. After the user has then been authenticated, the provider will redirect the user back to your application.

The simplest way to handle the callback is to create a page for it:

// src/pages/AuthCallback

import React from 'react';
import { RouteComponentProps } from '@reach/router';
import { useAuth } from 'react-auth-hook';

export function AuthCallback(props: RouteComponentProps) {
	const { handleAuth } = useAuth();

	React.useEffect(() => {
		handleAuth();
	}, []);

	return (
		<>
			<h1>You have reached the callback page</h1>
			<h2>you will now be redirected</h2>
		</>
	);
}

The purpose of this page is to show some "loading" state and then run the handleAuth method from useAuth on page load. The function will automatically redirect the user to the root route (/).

3. Authenticating Users

Now you are done with the hard part that is configuring the Auth0 and the library. Now all that is left to do, is to authenticate your users in your application:

// src/pages/Home

import React from 'react';
import { useAuth } from 'react-auth-hook';

export function Home() {
	const { isAuthenticated, login, logout } = useAuth();
	return isAuthenticated() ? (
		<button onClick={login}>log in</button>
	) : (
		<button onClick={logout}>log out</button>
	);
}

For a full example, check out the examples folder in this repository.

Documentation

AuthProvider

The AuthProvider component implements the AuthProvider interface and takes a number of props to initialise the Auth0 client and more.

interface AuthProvider {
	auth0Domain: string;
	auth0ClientId: string;
	auth0Params?: Omit<
		Auth0.AuthOptions,
		| 'domain'
		| 'clientId'
		| 'redirectUri'
		| 'audience'
		| 'responseType'
		| 'scope'
	>;
	navigate: any;
	children: React.ReactNode;
}

As can be seen from the type interface, the AuthProvider API takes a couple of configuration options:

  • auth0Domain the auth domain from your Auth0 application
  • auth0ClientId the client id from your Auth0 application
  • auth0Params additional parameters to pass to Auth0.WebAuth
  • navigate your routers navigation function used for redirects

Default Auth0 Configuration

react-auth-hook infers and sets a few defaults for the configuration parameters required by auth0-js:

// AuthProvider.tsx

const callbackDomain = window
	? `${window.location.protocol}//${window.location.host}`
	: 'http://localhost:3000';

const auth0Client = new Auth0.WebAuth({
	domain: auth0Domain,
	clientID: auth0ClientId,
	redirectUri: `${callbackDomain}/auth_callback`,
	audience: `https://${auth0Domain}/api/v2/`,
	responseType: 'token id_token',
	scope: 'openid profile email',
});

The domain and clientID comes from the AuthProvider props.

The redirectUri is configured to use the /auth_callback page on the current domain which is inferred automatically as can be seen above. Auth0 redirect your users to this page after login so you can set initialise the user session. useAuth handles all this for you.

The audience is used for requesting API access and is set to v2 of the Auth0 API by default.

The responseType specifies which response we want back from the Auth0 API, here being the token and id_token.

The scope is set here is the default in auth0-js as of version 9. It specifies what user resources you will gain access to on successful authentication.

useAuth

The useAuth hook implements the UseAuth interface and exposes a number of functions and data objects.

interface UseAuth {
	login: () => void;
	logout: () => void;
	handleAuth: (returnRoute?: string) => void;
	isAuthenticated: () => boolean;
	user: Auth0.Auth0UserProfile | null;
	authResult: Auth0.Auth0DecodedHash | null;
}

login

The login function calls the authorize function from Auth0 and redirects the user to the Auth0 hosted login page (/authorize) in order to initialize a new authN/authZ transaction using the Universal Login.

logout

The logout function calls the similarly named function from Auth0. After a successful logout, the users will be routed to the some-domain URLs that you whitelisted in the Auth0 configuration step.

handleAuth

The handleAuth function takes care of - as the name suggests - handling the authentication. The method will create a cookie in local storage with your user's information and redirect back to the homepage (/) by default.

If your users have navigated directly to a nested route within your site, you are probably going to want to redirect them back to that route. Ro redirect to a route other than the homepage, supply the returnRoute argument with the associated route. For example, to dynamically redirect to a nested route after authentication, call handleAuth like so:

handleAuth(window.location.href.replace(window.location.origin, ''));

isAuthenticated

The isAuthenticated function returns a boolean depending on wether the users is authenticated or not. It utilises the expiration time for the auth token provided by authResult returned by a successful login. The useAuth reducer sets and read this token in localStorage.

user

The user object contains the Auth0 user profile returned when the users is successfully authenticated. It implements the Auth0UserProfile interface. A detailed description of the interface can be found in the auth0-js types.

authResult

The authResult object contains the decoded Auth0 hash which is the object returned by the parseHash function. It implements the Auth0DecodedHash interface which you can see here:

interface Auth0DecodedHash {
	accessToken?: string;
	idToken?: string;
	idTokenPayload?: any;
	appState?: any;
	refreshToken?: string;
	state?: string;
	expiresIn?: number;
	tokenType?: string;
	scope?: string;
}

Issues

If any issues occur using this library, please fill our a detailed bug report on GitHub.

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].