- Notifications
You must be signed in to change notification settings - Fork112
The simplest way to add authentication to your React app. Supports various providers.
License
Swizec/useAuth
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The simplest way to add authentication to your React app. Handles everything for you. Users, login forms, redirects, sharing state between components. Everything
useAuth is designed to be quick to setup. You'll need an Auth0 account with an app domain and client id.
$ yarn add react-use-authDownloads from npm, adds to your package.json, etc. You can usenpm as well.
useAuth uses anAuthProvider component to configure the Auth0 client and share state between components. It's using React context with a reducer behind the scenes, but that's an implementation detail.
I recommend adding this around your root component. In Gatsby that's done ingatsby-browser.js andgatsby-ssr.js. YesuseAuth is built so it doesn't break server-side rendering. ✌️
But of course server-side "you" will always be logged out.
// gatsby-browser.jsimportReactfrom"react";import{navigate}from"gatsby";import{AuthProvider}from"react-use-auth";exportconstwrapRootElement=({ element})=>(<AuthProvidernavigate={navigate}auth0_domain="useauth.auth0.com"auth0_client_id="GjWNFNOHq1ino7lQNJBwEywa1aYtbIzh">{element}</AuthProvider>);
<AuthProvider> creates a context, sets up a state reducer, initializes an Auth0 client and so on. Everything you need for authentication to work in your whole app :)
The API takes a couple config options:
navigate– your navigation function, used for redirects. I've tested with Gatsby, but anything should workauth0_domain– from your Auth0 appauth0_client_id– from your Auth0 appauth0_params– an object that lets you overwrite any of the default Auth0 client parameters
PS: even though Auth doesn't do anything server-side, useAuth will throw errors during build, if its context doesn't exist
By defaultuseAuth's Auth0 client uses these params:
constparams={domain:auth0_domain,clientID:auth0_client_id,redirectUri:`${callback_domain}/auth0_callback`,audience:`https://${auth0_audience_domain||auth0_domain}/api/v2/`,responseType:"token id_token",scope:"openid profile email"};
domain andclientID come from your props.
redirectUri is set to use theauth0_callback page on the current domain. Auth0 redirects here after users login so you can set cookies and stuff.useAuth will handle this for you ✌️
audience is set to use api/v2. I know this is necessary but honestly have been copypasting it through several of my projects. You can define a custom audience domain withauth0_audience_domain.
responseType same here. I copy paste this from old projects so I figured it's a good default.
scope you needopenid for social logins and to be able to fetch user profiles after authentication. Profile and Email too. You can add more via theauth0_params override.
Auth0 and most other authentication providers use OAuth. That requires redirecting your user totheir login form. After login, the provider redirects the user back toyour app.
Any way of creating React pages should work, here's what I use for Gatsby.
// src/pages/auth0_callbackimportReact,{useEffect}from"react";import{useAuth}from"react-use-auth";importLayoutfrom"../components/layout";constAuth0CallbackPage=()=>{const{ handleAuthentication}=useAuth();useEffect(()=>{handleAuthentication();},[]);return(<Layout><h1> This is the auth callback page, you should be redirected immediately.</h1></Layout>);};exportdefaultAuth0CallbackPage;
The goal is to load a page, briefly show some text, and run thehandleAuthentication method fromuseAuth on page load.
That method will create a cookie in local storage with your user's information and redirect back to the homepage by default.
To redirect to a route other than the homepage after the user is logged in, supply thehandleAuthentication function an Object Literal with thepostLoginRoute key and an associated route value. For example, to route to/account, callhandleAuthentication as follows:
handleAuthentication({postLoginRoute:"/account"});
PS: Make sure you add<domain>/auth0_callback as a valid callback URL in your Auth0 config
You're ready to useuseAuth for authentication in your React app.
Here's a login button for example:
// src/pages/index.jsconstLogin=()=>{const{ isAuthenticated, login, logout}=useAuth();if(isAuthenticated()){return<ButtononClick={logout}>Logout</Button>;}else{return<ButtononClick={login}>Login</Button>;}};
isAuthenticated is a method that checks if the user's cookie is still valid.login andlogout trigger their respective actions.
You can even say hello to your users
// src/pages/index.jsconstIndexPage=()=>{const{ isAuthenticated, user}=useAuth()return(<Layout><SEOtitle="Home"/><h1>Hi{isAuthenticated() ?user.name :"people"}</h1>
CheckisAuthenticated then use the user object. Simple as that.
isAuthenticating is a flag for checking whether or notuseAuth is in the middle of validating login details. This allows you to then make requests to your user database and work out where to send users from theauth0_callback page, e.g. profile page or sign up.
constAuth0CallbackPage=()=>{const{ user, isAuthenticating, handleAuthentication}=useAuth();const{ loading, data, error}=useQuery(QUERY,{variables:{id:user.sub}});if(error){return<h1>There was an error</h1>;}if(isAuthenticating||loading){return(<h1> This is the auth callback page, you should be redirected immediately.</h1>);}const{user:dbUser}=data||{};constredirectUrl=dbUser ?"/app/profile" :"/app/signup";handleAuthentication({postLoginRoute:redirectUrl});};
There's a couple of required configurations you need to make in Auth0 to make useAuth run smoothly.
Callback URLs
You need to allow both local development and your production app in callback URLs. It's a whitelist that tells Auth0 that your login request is coming from the right source.
useAuth avoids using local storage for secure tokens. For Auth0 to know that ourcheckSession request is coming from the right source, you need to add your URLs to allowed web origins.
Allowed logout urls
After logging out, Auth0 redirects back to your app. Again, it needs to know you aren't up to anything shady. If you are getting 400 response errors on page load, this is the most likely culprit.
NB Make sure you're not blocking cookies! Extensions like privacy badger and the Brave browser will prevent Auth0 from setting cookies so refreshing between logins wont work
After you've set everything up (and you're using social sign on methods) you'll notice that refreshing doesn't keep your user logged in... 👎
If you're using an IdP such as Google or Github to provide identity, you will need to register an app on Auth0 to enable this behaviour. The steps to create this behaviour are a bit nested in docs but can be achieved relatively simply by following the guideSet Up Social Connections on the Auth0 site. The guide follows steps for Google sign on, your mileage with other providers may vary...
For a more detailed understanding of why this is happening you can have a read throughthis section of Auth0s guide to setting up a secure React application. (Pro tip: search forKeeping Users Signed In after a Refresh to jump straight to the section in question).
Since version 0.4.0 useAuth exposes the entire Auth0 authResult object so you can access your user's id or access token. This is useful when you have to log the user into your own backend as well as the frontend.
For reference:
Like this:
functionSomeComponent(){const{ authResult}=useAuth();console.log(authResult.idToken);console.log(authResult.accessToken);// etc, I recommend printing the authResult object to see everything that's available}
Since version 0.7.0 useAuth supports role-based permissions. Using roles, you can granularly control which parts of your site are available to which users.
You'll need to add some config on Auth0 and when using useAuth.
Auth0 rules are little snippets of JavaScript that run when you request user data.
Go toRules and clickCreate Rule. Start an empty rule and add this code:
function(user,context,callback){constnamespace='https://YOUR_DOMAIN';constassignedRoles=(context.authorization||{}).roles;user.user_metadata=user.user_metadata||{};user.user_metadata.roles=assignedRoles;context.idToken[namespace+'/user_metadata']=user.user_metadata;callback(null,user,context);}
This rule adds user roles to their meta data. You have to define thenamespace. Make sure it looks like a URL.
When rendering your<AuthProvider> add the custom property namespace. Make sure it matches the namespace you used above.
exportconstwrapPageElement=({ element, props})=>(<AuthProvidernavigate={navigate}// ...customPropertyNamespace="https://YOUR_DOMAIN">
Now you can useisAuthorized to check if the current user has access to some part of your site.
// show something only if current user has Student role{isAuthorized("Student") ?(<Content{...props}fullwidth={fullwidth}menu={menu}setMenu={setMenu}nav={nav}/> :null}// you can also use an OR'd array// show something if user has Student role OR Admin role{isAuthorized(["Student","Admin"]) ?(<Content{...props}fullwidth={fullwidth}menu={menu}setMenu={setMenu}nav={nav}/> :null}
If current user is authenticatedand has theStudent role, show the content. Otherwise null.
For convenience you can also pass multiple roles to check with an OR condition. If any fit the current user,isAuthorized returnstrue.
You can try it out here 👉https://gatsby-useauth-example.now.sh/
👤Swizec Tellerswizec@swizec.com
- Github:@swizec
- Twitter:@swizec
- Blog:swizec.com/blog
Contributions, issues and feature requests are welcome!
Feel free to checkissues page.
I am looking to support other authentication providers. Please help :)
Give a ⭐️ if this project helped you!
Copyright © 2019Swizec Tellerswizec@swizec.com.
This project isMIT licensed.
This README was generated with ❤️ byreadme-md-generator
Thanks goes to these wonderful people (emoji key):
This project follows theall-contributors specification. Contributions of any kind welcome!
About
The simplest way to add authentication to your React app. Supports various providers.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.




