This demo will showcase how to use the Auth0 SDK with a Next JS server rendered application. It will also show how you can authenticate and refresh sessions.
- Getting Started
- Setup Auth0
- Whitelist Routes
- Quick Start
- Provide Auth0 Credentials
- Run The App
- Log In/ Sign Up
- Logout
- Refresh Token
You must have access to a computer with at least NODE JS version 6 or higher installed.
Ensure that if you have all this configured, you can go on ahead to the quick start section.
Setup Auth0
To complete this step, you will need an Auth0 account. If you don't have one, you can create one at the Auth0 Website.
Create a new application via your Auht0 account dashbaord. Since we are working with Next JS, we will select the web application option as the type of our Auth0 Application, just in case we need to use some server-side capabilities of the Auht0 SDK.
The next step is to tell Auth0 about the routes that an authentication step will redirect to. You need to explicitly whitelist each possible route for security reasons so Auth0 will only redirect to allowed routes. By default, we will be using "http://localhost:8000/callback" for development. When you go into production, make sure you add any production route to this list.
Clone the repository into your machine and open up services/auth.js.
In this file you will need to provide some credentials which can be found on the dashboard for your corresponding Auth0 application. The Auth class inside the auth.js file is a service that wraps around the Auth0 SDK. The configuration part is the WebAuth function which configures the Auth0 SDK.
auth0 = new auth0.WebAuth({ domain: 'YOUR.DOMAIN.AUTH0.COM', clientID: 'CLIENT_ID', redirectUri: 'http://localhost:8000/callback //DEFAULT FOR THIS APP', audience: 'AUDIENCE', responseType: 'RESPONSE1 RESPONSE2', scope: 'SCOPE1 SCOPE2 ...' });
In this file, the DOMAIN & CLIENT ID are the 2 mandatory parameters you need to provide to the WebAuth configuration. You can find more information about other conifguration parmeters at the Auth0 SDK Documentation
npm install npm run dev
Your application will be launched on localhost:8000. You can play around with the application and try to log in and log out.
The auth.js is a wrapper for Auth0 SDK and exposes some basic functionality that allows you to log in, logout & refresh your token.
The login flow basically routes you to the intermediary page "sign-in.js" which basically processes the request and hands over to Auth0 SDK for login. The reason for this is to keep bookmarking working with ease.
Sign-in.js
componentDidMount(){ if (auth0.isAuthenticated()){ Router.push('/'); } else { auth0.login(); } }
We also put a route guard to ensure that if you are already logged in you go back to the home page and if not, you are redirected to login.
Login Function
The login function made available in the "Auth" service found in the "auth.js" file basically calls the Auth0 SDK to log you in
login() { this.auth0.authorize(); }
After the login is successful, Auth0 will redirect you to the callback route which is whitelisted and in there you will be able to save the user token and any information you need to localstorage or your preferred storage mechanism.
Callback.js
componentDidMount(){ if (auth0.isAuthenticated()){ Router.push('/'); } else { auth0.handleAuthentication() } }
auth.js
handleAuthentication() { this.auth0.parseHash({hash: window.location.hash}, (err, authResult)=> { if (authResult && authResult.accessToken && authResult.idToken) { console.log(authResult); this.setSession(authResult); Router.push('/'); } else if (err) { Router.push('/sign-in'); console.log(err); } }); } setSession(authResult) { // Set the time that the Access Token will expire at let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime()); localStorage.setItem('access_token', authResult.accessToken); localStorage.setItem('id_token', authResult.idToken); localStorage.setItem('expires_at', expiresAt); }
The logout functionality simply just removes all saved data from the persistent storage so it cannot be used for future requests.
auth.js
logout() { // Clear Access Token and ID Token from local storage localStorage.removeItem('access_token'); localStorage.removeItem('id_token'); localStorage.removeItem('expires_at'); }
You might need to ensure that you want to refresh your token pretty often. This is very useful when you work with security intensive applications. Auth0 handles this very maturely in a silent manner. The "refreshToken" function calls Auth0 SDKs' "checkSession" function. It is also necessary to ensure that if you need this feature, the "responseMode" parameter when configuring Auth0 with the "WebAuth" function is set to "web_message" to allow this technique to work properly.
Configuration
auth0 = new auth0.WebAuth({ domain: 'YOUR.DOMAIN.AUTH0.COM', clientID: 'CLIENT_ID', redirectUri: 'http://localhost:8000/callback //DEFAULT FOR THIS APP', responseMode: 'web_message', audience: 'AUDIENCE', responseType: 'RESPONSE1 RESPONSE2', scope: 'SCOPE1 SCOPE2 ...' });
Token Refresh
refreshToken(){ this.auth0.checkSession(); }
You can find documentation for further configuration of the token refresh with "checkSession" at the documentation page for the checkSession function.
Auth0 has another technique for authenticating users. This involes the use of Lock, an embedded Auth0 client. For more on this, please visit the Lock documentation and also have a look at a Next JS Auth0 starter project that uses Lock.
Some common errors include forgetting npm install before running. This is very important and mandatory step. It is also very important to use your own AUTH0 Credentials. If ther are any errors, please feel free to post an issue.