Vue

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • Vue.js 1.0.16
Show requirements

Before Starting

Please remember that for security purposes, you have to register the URL of your app in the Application Settings section as the callbackURL.

Right now, that callback is set to the following:

https://YOUR_APP/callback

1. Add the Auth0 Scripts

Add Lock to your index.html file and set the viewport.

<!-- Auth0 Lock script -->
<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>

<!-- Setting the right viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

2. Set Up Login and Logout on a Standard Vue Instance (No Routing)

If your app does not require routing, set up a standard Vue.js instance that is attached to a DOM element.

2.1 Login

On the Vue instance, create a login method that calls lock.

// app.js

new Vue({
  el: '#app',
  data() {
    return {
      authenticated: false,
      secretThing: '',
      lock: new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN')
    }
  },
  ready() {
    var self = this;
    
    this.authenticated = checkAuth();
    
    this.lock.on('authenticated', (authResult) => {
      console.log('authenticated');
      localStorage.setItem('id_token', authResult.idToken);
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          return;
        }
        // Set the token and user profile in local storage
        localStorage.setItem('profile', JSON.stringify(profile));

        this.authenticated = true;
      });
    });

    this.lock.on('authorizaton_error', (error) => {
      // handle error when authorizaton fails
    });
  },
  methods: {
    login() {
      this.lock.show();
    }
  }
});

In this example, the Vue instance is attached to an element with an ID of app. The authenticated property is used to keep track of the user's authentication state and is initially set to false. It is set to true upon a successful login. When the user authenticates successfuly, their profile and token are saved in local storage.

2.2 Logout

To log the user out, simply remove their profile and token from local storage.

// app.js

methods: {
  logout() {
    // To log out, we just need to remove the token and profile
    // from local storage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.authenticated = false;
  },
}

These methods can now be attached to elements in the template.

  <!-- index.html -->
  
  <button @click="login()" v-show="!authenticated">Login</button>
  <button @click="logout()" v-show="authenticated">Logout</button>  

Note: There are multiple ways of implementing login. The example above displays the Lock Widget. However you may implement your own login UI by changing the line <script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script> to <script src="https://cdn.auth0.com/w2/auth0-7.4.min.js"></script>.

3. Make Secure Calls to an API

To make secure calls to an API, attach the user's JWT as an Authorization header to the HTTP request. Be sure that you have vue-resource in your project to make HTTP requests.

// app.js

methods: {
  // Make a secure call to the server by attaching
  // the user's JWT as an Authorization header
  getSecretThing() {
    var jwtHeader = { 'Authorization': 'Bearer ' + localStorage.getItem('id_token') };
    this.$http.get('http://localhost:3001/secured/ping', (data) => {
      console.log(data);
      this.secretThing = data.text;
    }, {
      headers: jwtHeader
    }).error((err) => console.log(err));
  }
}

This method can then be used in your template to make the API call.

  <!-- index.html -->
  
  <button @click="getSecretThing()">Get Secret Thing</button>

4. Implement Routing

For routing in a single page Vue.js app, use vue-router. To make use of the router, create Vue components for your application's states.

// app.js

// The public route can be viewed at any time
var Public = Vue.extend({
  template: `<p>This is a public route</p>`
});

// The private route can only be viewed when
// the user is authenticated. The canActivate hook
// uses checkAuth to return true if the user is authenticated
// or false if not.
var Private = Vue.extend({
  template: `<p>This is a private route. If you are reading this, you are authenticated.</p>`,
  route: {
    canActivate() {
      return checkAuth();
    }
  }
});

var App = Vue.extend({
  template: `
    <h1>Vue.js with Auth0</h1>
    <button @click="login()" v-show="!authenticated">Login</button>
    <button @click="logout()" v-show="authenticated">Logout</button>
    <hr>
    <button v-link="'public'">Public Route</button>
    <button v-link="'private'" v-show="authenticated">Private Route</button>
    <router-view></router-view>
    <hr>
    <div v-show="authenticated">
      <button @click="getSecretThing()">Get Secret Thing</button>
      <h3>{{secretThing}}</h3>
    </div>
  `,
  data() {
    return {
      authenticated: false,
      secretThing: '',
      lock: new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN')
    }
  },
  // Check the user's auth status when the app
  // loads to account for page refreshing
  ready() {
    this.authenticated = checkAuth();
    this.lock.on('authenticated', (authResult) => {
      console.log('authenticated');
      localStorage.setItem('id_token', authResult.idToken);
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          return;
        }
        // Set the token and user profile in local storage
        localStorage.setItem('profile', JSON.stringify(profile));

        this.authenticated = true;
      });
    });
    this.lock.on('authorizaton_error', (error) => {
      // handle error when authorizaton fails
    });
  },
  methods: {
    login() {
      this.lock.show();
    },
    logout() {
      // To log out, we just need to remove the token and profile
      // from local storage
      localStorage.removeItem('id_token');
      localStorage.removeItem('profile');
      this.authenticated = false;
    },
    // Make a secure call to the server by attaching
    // the user's JWT as an Authorization header
    getSecretThing() {
      var jwtHeader = { 'Authorization': 'Bearer ' + localStorage.getItem('id_token') };
      this.$http.get('http://localhost:3001/secured/ping', (data) => {
        console.log(data);
        this.secretThing = data.text;
      }, {
        headers: jwtHeader
      }).error((err) => console.log(err));
    }
  }
});

// Utility to check auth status
function checkAuth() {
  return !!localStorage.getItem('id_token');
}

var router = new VueRouter({
  history: true
});

router.map({
  '/public': {
    component: Public
  },
  '/private': {
    component: Private
  }
});

router.start(App, '#app');

The canActivate lifecycle hook is used to determine whether the route can be navigated to. If the user has a JWT in local storage, they are able to reach the route. The checkAuth method is used to check for the presence of a JWT in local storage.

5. Intercept Unauthorized Requests

An HTTP interceptor can be used to define custom actions for any unauthorized requests. In many cases, an HTTP 401 will be returned when the user's JWT is expired or otherwise invalid. When this happens, you will likely want to invalidate the user's authenticated state on the front end and redirect them to the home or login route.

// app.js

// Intercept responses and check for anything
// unauthorized. If there is an unauthorized response,
// log the user out and redirect to the home route
Vue.http.interceptors.push({
  response: function (response) {
    if(response.status === 401) {
      this.logout();
      this.authenticated = false;
      router.go('/');
    }
    return response;
  }
});

Persisting Application State

Lock uses redirect mode by default, meaning that a full page refresh will occur when users go through the authentication process in your application. This can be undesirable in single page apps, especially if the application contains state that should be displayed to the user again after they authenticate. For example, it may be the case that your users can initiate authentication from an arbitrary route within your single page app and you may want to return them to that location (along with any relevant state) after authentication is complete.

The recommended solution for this is to persist any necessary application state in local storage or a cookie before the user logs in or signs up. With this data, you can provide some custom post-authentication logic in the listener for the authenticated event to allow the user to pick up from where they left off.

In cases where storing application state is not possible, Lock's popup mode can be used. Please note that popup mode is not recommended. Known bugs in certain browsers prevent popup mode from functioning as expected under some circumstances.

Use Auth0 for FREECreate free Account