This tutorial demonstrates how to add user login to a Vue.JS application using Auth0. We recommend you to Log in to follow this quickstart with examples configured for your account.
I want to integrate with my app15 minutes
I want to explore a sample app2 minutes
Get a sample configured with your account settings or check it out on Github.
Get Your Application Keys
When you signed up for Auth0, a new application was created for you, or you could have created a new one.
You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.
You need the following information:
- Client ID
Configure Callback URLs
A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.
You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Application Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.
Configure Logout URLs
A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the
returnTo query parameter.
You can set the logout URL for your app in the Allowed Logout URLs field in your Application Settings. If you don't set a logout URL, your users will be unable to log out of the application and will get an error.
Configure Allowed Web Origins
You need to whitelist the URL for your app in the Allowed Web Origins field in your Application Settings. If you don't whitelist your application URL, the application will be unable to automatically refresh the authentication tokens and your users will be logged out the next time they visit the application, or refresh the page.
Integrate Auth0 in your Application
You need the auth0.js library to integrate Auth0 into your application. You can either install the library locally in your application or load it from CDN.
Loading via dependencies
Install auth0.js using npm or yarn.
Once you install auth0.js, add it to your build system or bring it in to your project with a script tag.
Loading it from CDN
If you do not want to use a package manager, you can retrieve auth0.js from Auth0's CDN.
Authentication with Auth0
Universal Login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your Vue.js application.
When a user logs in, Auth0 returns three items:
access_token: to learn more, see the Access Token documentation
id_token: to learn more, see the ID Token documentation
expires_in: the number of seconds before the Access Token expires
You can use these items in your application to set up and manage authentication.
Create an Authentication Service
The best way to manage and coordinate the tasks necessary for user authentication is to create a reusable service. With the service in place, you will be able to call its methods throughout your application. The name for it is at your discretion, but in these examples it will be called
AuthService and the filename will be
authService.js. An instance of the
WebAuth object from auth0.js can be created in the service.
Create a service and instantiate
auth0.WebAuth. Provide a method called
login which calls the
authorize method from auth0.js.
To provide the values for
domain, create a new file
auth_config.json in the root directory of the application alongside your
package.json file, and populate it with your tenant values:
Handle Authentication Tokens
Add some additional methods to
AuthService to fully handle authentication in the app.
The service now includes several other methods for handling authentication.
handleCallback- looks for an authentication result in the URL hash and processes it with the
parseHashmethod from auth0.js
Dateobject can be used
renewTokens- uses the
checkSessionmethod from auth0.js to renew the user's authentication status, and calls
localLoginif the login session is still valid
logout- removes the user's tokens from memory. It also calls
webAuth.logoutto log the user out at the authorization server
isAuthenticated- checks whether the local storage flag is present and equals "true", and that the expiry time for the ID Token has passed
About the Authentication Service
When you set up the
AuthService service, you create an instance of the
auth0.WebAuth object. In that instance, you can define the following:
- Configuration for your application and domain
- Response type, to show that you need a user's ID Token after authentication
- The URL where you want to redirect your users after authentication.
Your users authenticate via Universal Login, at the login page. They are then redirected back to your application. Their redirect URLs contain hash fragments with the user's ID token.
You can get the tokens from the URL using the
parseHash method in the auth0.js library. You can then set up the login session using the
localLogin method. The
localLogin method uses the
exp value from the ID Token payload to calculate when the user's ID Token expires.
Authentication using JSON Web Tokens is stateless. This means that when you use it, no information about the user's session is stored on your server.
To set up a session for the user on the client side, save the
id_token value into memory, and write a flag to local storage to indicate that the user is logged in.
To log the user out, remove the
id_token value from memory and remove the flag from local storage.
You need to provide a way for your application to recognize if the user is authenticated. To do that, use the
isAuthenticated method to check if the user's ID Token has expired. The user is no longer authenticated when the expiry time of their ID Token passes.
Create a Vue Plugin
So that the authentication service may be passed around easily to each component, create a Vue.js plugin that will inject the service into everywhere that needs it:
This plugin provides access to the
AuthService class from each component, through the
this.$auth property. It also provides a mechanism for when the login state changes, for components that implement a
main.js and install the plugin:
Provide a Login Control
Provide a component with controls for the user to log in and log out.
@click events on the Log In and Log Out buttons make the appropriate calls to the
AuthService to allow the user to log in and log out. Notice that these buttons are conditionally hidden and shown depending on whether or not the user is currently authenticated.
Also notice the use of
this.$auth to access the
AuthService instance. Login events can be handled by providing a
handleLoginEvent method on any component.
When the Log In button is clicked, the user will be redirected to login page.
When the application first starts up, a call to
renewTokens is made that tries to reinitialize the user's login session, if it is detected that they should already be logged in. This would be the case, for example, if the user logged in and then refreshed the browser window.
Add a Callback Component
Using Universal Login means that users are taken away from your application to a login page hosted by Auth0. After they successfully authenticate, they are returned to your application where a client-side session is set for them.
You can select any URL in your application for your users to return to. We recommend creating a dedicated callback route. If you create a single callback route:
- You don't have to whitelist many, sometimes unknown, callback URLs.
- You can display a loading indicator while the application sets up a client-side session.
When a user authenticates at the login page and is then redirected back to your application, their authentication information will be contained in a URL hash fragment. The
handleAuthentication method in the
AuthService is responsible for processing the hash.
vue-router to allow callbacks to be routed properly to the
Create a component named
Callback and populate it with a loading indicator. The component should also call
handleAuthentication from the
Add a new file
router.js inside the
src folder with the following content:
main.js to register the router:
After authentication, users will be taken to the
/callback route for a brief time where they will be shown a loading indicator. Their client-side session will be set during this time, after which they will be redirected to the
Display the User's Profile
AuthService has already extracted the user's profile information and stored it in memory, and can be accessed using
this.$auth.profile from inside a Vue component.
To display the profile information, create a new component
Profile in the
Profile component into
router.js and then modify the routes list so that the
Profile component is mapped to
Then add the
/profile route to your navigation bar by inserting a new
<li> element into the navigation bar structure:
Securing the profile route
Even though the
/profile route is only shown if the user is authenticated, the user could still manually type the URL into the browser and access the page if they have not logged in — although there will be nothing to see.
A catch-all rule can be added to the router so that access is only permitted if the user is logged in. If they are not logged in, they will be prompted to log in before being redirected to the location they tried to access in the first place.
router.js and add a rule that exhibits this behavior:
Given this, any page that is not either the home page or the callback URL will cause the application to show the login prompt if the user is not authenticated.
See it in action
Install the dependencies, start your app and point your browser to http://localhost:3000. Follow the Log In link to log in or sign up to your Auth0 tenant. Upon successful login or signup, you should be redirected to the user's profile page.