Vue

View on Github

Vue

Gravatar for andres.aguiar@auth0.com
By Andres Aguiar
Auth0

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 explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Vue 2.3.4

New to Auth? Learn How Auth0 works, how it integrates with Single Page Applications and which protocol it uses.

Configure Auth0

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
  • Domain

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

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.

If you are following along with the sample project you downloaded from the top of this page, you should set the Allowed Callback URL to http://localhost:3000/callback.

Integrate Auth0 in your Application

Install auth0.js

You need the auth0.js library to integrate Auth0 into your application.

Install auth0.js using npm or yarn.

# installation with npm
npm install --save auth0-js

# installation with yarn
yarn add auth0-js

Once you install auth0.js, add it to your build system or bring it in to your project with a script tag.

<script type="text/javascript" src="node_modules/auth0-js/build/auth0.js"></script>

If you do not want to use a package manager, you can retrieve auth0.js from Auth0's CDN.

<script src="https://cdn.auth0.com/js/auth0/9.5.1/auth0.min.js"></script>

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.

You can also embed the login dialog directly in your application using the Lock widget. If you use this method, some features, such as single sign-on, will not be accessible. To learn how to embed the Lock widget in your application, follow the Embedded Login sample.

When a user logs in, Auth0 returns three items:

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'll 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.

// src/Auth/AuthService.js

import auth0 from 'auth0-js'
import { AUTH_CONFIG } from './auth0-variables'
import EventEmitter from 'eventemitter3'
import router from './../router'

export default class AuthService {

  constructor () {
    this.login = this.login.bind(this)
    this.setSession = this.setSession.bind(this)
    this.logout = this.logout.bind(this)
    this.isAuthenticated = this.isAuthenticated.bind(this)
  }

  auth0 = new auth0.WebAuth({
    domain: 'YOUR_AUTH0_DOMAIN',
    clientID: 'YOUR_CLIENT_ID',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token id_token',
    scope: 'openid'
  })

  login () {
    this.auth0.authorize()
  }
}

Checkpoint: Try calling the login method from somewhere in your application. This could be from a button click or in some lifecycle event, just something that will trigger the method so you can see the login page.

hosted login

Handle Authentication Tokens

Add some additional methods to the Auth service to fully handle authentication in the app.

Install the EventEmitter required by the service.

npm install --save EventEmitter

// src/Auth/AuthService.js

import auth0 from 'auth0-js'
import EventEmitter from 'EventEmitter'
import router from './../router'

export default class AuthService {

  authenticated = this.isAuthenticated()
  authNotifier = new EventEmitter()

  constructor () {
    this.login = this.login.bind(this)
    this.setSession = this.setSession.bind(this)
    this.logout = this.logout.bind(this)
    this.isAuthenticated = this.isAuthenticated.bind(this)
  }

  // ...
  handleAuthentication () {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult)
        router.replace('home')
      } else if (err) {
        router.replace('home')
        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)
    this.authNotifier.emit('authChange', { authenticated: true })
  }

  logout () {
    // Clear Access Token and ID Token from local storage
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('expires_at')
    this.userProfile = null
    this.authNotifier.emit('authChange', false)
    // navigate to the home route
    router.replace('home')
  }

  isAuthenticated () {
    // Check whether the current time is past the
    // Access Token's expiry time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
    return new Date().getTime() < expiresAt
  }
}

The service now includes several other methods for handling authentication.

  • handleAuthentication - looks for an authentication result in the URL hash and processes it with the parseHash method from auth0.js
  • setSession - sets the user's Access Token, ID Token, and a time at which the Access Token will expire
  • logout - removes the user's tokens from browser storage
  • isAuthenticated - checks whether the expiry time for the Access 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 Access Token and an ID Token after authentication
  • Audience and scope, specifying that you need an access_token that can be used to invoke the /userinfo endpoint.
  • The URL where you want to redirect your users after authentication.

In this tutorial, the route is /callback, which is implemented in the Add a Callback Component step.

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 each user's authentication information:

  • access_token
  • id_token
  • expires_in

You can get the tokens from the URL using the parseHash method in the auth0.js library. You can save the values in local storage with the setSession method. The setSession method uses the expires_in value from the URL hash fragment to calculate when the user's Access 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 following information in browser storage:

  • access_token
  • id_token
  • expires_in

To log the user out, you must remove these values from the storage.

The examples below use local storage to save the user's authentication information. You can also use session storage or cookies.

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 Access Token has expired. The user is no longer authenticated when the expiry time of their Access Token passes.

Provide a Login Control

Provide a component with controls for the user to log in and log out.

// src/App.vue

<template>
  <div>
    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">Auth0 - Vue</a>

          <router-link :to="'/'"
            class="btn btn-primary btn-margin">
              Home
          </router-link>

          <button
            class="btn btn-primary btn-margin"
            v-if="!authenticated"
            @click="login()">
              Log In
          </button>

          <button
            class="btn btn-primary btn-margin"
            v-if="authenticated"
            @click="logout()">
              Log Out
          </button>

        </div>
      </div>
    </nav>

    <div class="container">
      <router-view 
        :auth="auth" 
        :authenticated="authenticated">
      </router-view>
    </div>
  </div>
</template>

<script>

import AuthService from './auth/AuthService'

const auth = new AuthService()

const { login, logout, authenticated, authNotifier } = auth

export default {
  name: 'app',
  data () {
    authNotifier.on('authChange', authState => {
      this.authenticated = authState.authenticated
    })
    return {
      auth,
      authenticated
    }
  },
  methods: {
    login,
    logout
  }
}
</script>

<style>
@import '../node_modules/bootstrap/dist/css/bootstrap.css';
</style>

.btn-margin {
  margin-top: 7px
}

This example uses Bootstrap styles, but that's unimportant. Use whichever style library you like, or don't use one at all.

The @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.

When the Log In button is clicked, the user will be redirected to login page.

The login page uses the Lock widget. To learn more about Universal Login and the login page, see the Universal Login documentation. To customize the look and feel of the Lock widget, see the Lock customization options documentation.

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.

Create a component named CallbackComponent and populate it with a loading indicator. The component should also call handleAuthentication from the AuthService.

// src/components/Callback.vue

<template>
  <div class="spinner">
    <img src="../assets/loading.svg" alt="loading"/>
  </div>
</template>

<script>
  export default {
    name: 'callback',
    props: ['auth'],
    data () {
      this.auth.handleAuthentication()
      return {}
    }
  }
</script>

<style>
  .spinner {
    position: absolute;
    display: flex;
    justify-content: center;
    height: 100vh;
    width: 100vw;
    background-color: white;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
</style>

This example assumes some kind of loading spinner is available in the assets directory. See the downloadable sample for a demonstration.

After authentication, users will be taken to the /callback route for a brief time where they will be shown a loading indicator. During this time, their client-side session will be set, after which they will be redirected to the /home route.

This example assumes you are using path-based routing with mode: 'history'. If you are using hash-based routing, you won't be able to specify a dedicated callback route because the URL hash will be used to hold the user's authentication information.

Use Auth0 for FREE