vue logo
javascript logo

Vue.js Authentication By Example: Options API

Updated on January 30, 2023
Photo of Dan Arias
Dan AriasStaff Developer Advocate
Versions
Vue v2
Vue v3
Options
Composition API
Options API
Check out the "Vue.js By Example: Authentication Essentials" article to follow examples of the newest way to build secure Vue.js applications with the Vue.js 3 Composition API.

The Vue.js examples on this guide help you learn how to use the Vue.js Options API to implement the following security features:

  • How to add user login, sign-up, and logout to Vue.js applications.
  • How to create route guards to protect Vue.js application routes.
  • How to make API calls from Vue.js to request data from a protected API.
  • How to get user profile information to personalize a Vue.js user interface.

This guide uses the new Auth0 Vue SDK, which provides developers with a high-level API to handle many authentication implementation details. You can now secure your Vue.js applications following security best practices while writing less code.

Quick Vue.js Setup

With the help of Auth0 by Okta, you don't need to be an expert on identity protocols, such as OAuth 2.0 or OpenID Connect, to understand how to secure your web application stack.

You first integrate your Vue.js application with Auth0. Your application will then redirect users to an Auth0 customizable login page when they need to log in. Once your users log in successfully, Auth0 redirects them back to your Vue.js app, returning JSON Web Tokens (JWTs) with their authentication and user information.

Get the Vue.js Starter Application

We have created a starter project using create-vue to help you learn Vue.js security concepts through hands-on practice. You can focus on building Vue.js components with the Options API and services to secure your application.

Start by cloning the spa_vue_javascript_hello-world_options-api repository on its starter branch:

COMMAND
git clone -b starter https://github.com/auth0-developer-hub/spa_vue_javascript_hello-world_options-api.git

Once you clone the repo, make spa_vue_javascript_hello-world_options-api your current directory:

COMMAND
cd spa_vue_javascript_hello-world_options-api

Install the Vue.js project dependencies as follows:

COMMAND
npm install

This starter Vue.js Options API project offers a functional application that consumes data from an external API to hydrate the user interface. For simplicity and convenience, the starter project simulates the external API locally using json-server. Later on, you'll integrate this Vue.js Options API application with a real API server using a backend technology of your choice.

The compatible API server runs on http://localhost:6060 by default. As such, to connect your Vue.js Options API application with that API server, create a .env file under the root project directory:

COMMAND
touch .env

Populate it with the following environment variables:s

.env
VITE_API_SERVER_URL=http://localhost:6060

The official Vue.js build setup is now based on Vite, a front-end build tool that is lightweight and fast. Vite will only expose environment variables from .env to your Vite-processed code if those variables are prefixed with VITE_. This practice helps you prevent accidentally leaking your system's environment variables to your client application.

Next, execute the following command to run the JSON server API:

COMMAND
npm run api

Finally, open another terminal tab and execute this command to run your Vue.js Options API application:

COMMAND
npm run dev

You are ready to start implementing user authentication in this Vue.js Options API project. First, you'll need to configure the Vue.js application to connect successfully to Auth0. Afterward, you'll use the Auth0 Vue SDK to protect routes, display user profile information, and request protected data from an external API server to hydrate some of the application pages.

Configure Vue.js Options API with Auth0

Follow these steps to get started with the Auth0 Identity Platform quickly:

Sign up and create an Auth0 Application

A free account also offers you:

During the sign-up process, you create something called an Auth0 Tenant, representing the product or service to which you are adding authentication.

Once you sign in, Auth0 takes you to the Dashboard. In the left sidebar menu, click on "Applications".

Then, click the "Create Application" button. A modal opens up with a form to provide a name for the application and choose its type. Use the following values:

Name
Auth0 Vue.js Code Sample
Application Type
Single Page Web Applications
Single Page Web Applications

Click the "Create" button to complete the process. Your Auth0 application page loads up.

In the next step, you'll learn how to help Vue.js and Auth0 communicate.

What's the relationship between Auth0 Tenants and Auth0 Applications?

Let's say that you have a photo-sharing Vue.js app called "Vuetigram". You then would create an Auth0 tenant called vuetigram. From a customer perspective, Vuetigram is that customer's product or service.

Now, say that Vuetigram is available on three platforms: web as a single-page application and Android and iOS as a native mobile application. If each platform needs authentication, you need to create three Auth0 applications to provide the product with everything it needs to authenticate users through that platform.

Vuetigram users belong to the Auth0 Vuetigram tenant, which shares them across its Auth0 applications.

Create a communication bridge between Vue.js and Auth0

When using the Auth0 Identity Platform, you don't have to build login forms. Auth0 offers a Universal Login Page to reduce the overhead of adding and managing authentication.

How does Universal Login work?

Your Vue.js application will redirect users to Auth0 whenever they trigger an authentication request. Auth0 will present them with a login page. Once they log in, Auth0 will redirect them back to your Vue.js application. For that redirecting to happen securely, you must specify in your Auth0 Application Settings the URLs to which Auth0 can redirect users once it authenticates them.

As such, click on the "Settings" tab of your Auth0 Application page, locate the "Application URIs" section, and fill in the following values:

Allowed Callback URLs
http://localhost:4040/callback

The above value is the URL that Auth0 can use to redirect your users after they successfully log in.

Allowed Logout URLs
http://localhost:4040

The above value is the URL that Auth0 can use to redirect your users after they log out.

Allowed Web Origins
http://localhost:4040

Using the Auth0 Vue SDK, your Vue.js application will make requests under the hood to an Auth0 URL to handle authentication requests. As such, you need to add your Vue.js application origin URL to avoid Cross-Origin Resource Sharing (CORS) issues.

Scroll down and click the "Save Changes" button.

Do not close this page yet. You'll need some of its information in the next section.

Add the Auth0 configuration variables to Vue.js

From the Auth0 Application Settings page, you need the Auth0 Domain and Client ID values to allow your Vue.js application to use the communication bridge you created.

What exactly is an Auth0 Domain and an Auth0 Client ID?

Domain

When you created a new Auth0 account, Auth0 asked you to pick a name for your tenant. This name, appended with auth0.com, is your Auth0 Domain. It's the base URL that you will use to access the Auth0 APIs and the URL where you'll redirect users to log in.

You can also use custom domains to allow Auth0 to do the authentication heavy lifting for you without compromising your branding experience.

Client ID

Each application is assigned a Client ID upon creation, which is an alphanumeric string, and it's the unique identifier for your application (such as q8fij2iug0CmgPLfTfG1tZGdTQyGaTUA). You cannot modify the Client ID. You will use the Client ID to identify the Auth0 Application to which the Auth0 SPA SDK needs to connect.

Warning: Another critical piece of information present in the "Settings" is the Client Secret. This secret protects your resources by only granting tokens to requestors if they're authorized. Think of it as your application's password, which must be kept confidential at all times. If anyone gains access to your Client Secret, they can impersonate your application and access protected resources.

Head back to your Auth0 application page and click on the "Settings" tab.

Locate the "Basic Information" section and follow these steps to get the Auth0 Domain and Auth0 Client ID values:

Auth0 application settings to enable user authentication

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using these input fields makes it easy to copy and paste code as you follow along.

As such, enter the "Domain" and "Client ID" values in the following fields to set up your single-page application in the next section:

For security, these configuration values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

These variables let your Vue.js application identify itself as an authorized party to interact with the Auth0 authentication server.

Now, update the .env file under the Vue.js project directory as follows:

.env
VITE_API_SERVER_URL=http://localhost:6060
VITE_AUTH0_DOMAIN=AUTH0-DOMAIN
VITE_AUTH0_CLIENT_ID=AUTH0-CLIENT-ID
VITE_AUTH0_CALLBACK_URL=http://localhost:4040/callback

Once you reach the "Call a Protected API from Vue.js" section of this guide, you'll learn how to use VITE_API_SERVER_URL along with an Auth0 Audience value to request protected resources from an external API that is also protected by Auth0. For now, the application is using json-server to mock the API.

Handle the Auth0 post-login behavior

Notice that the Auth0 Callback URL, VITE_AUTH0_CALLBACK_URL, points to http://localhost:4040/callback, which is the URL that Auth0 uses to redirect your users after they successfully log in. For this Vue.js Options API application, you'll render a simple page component for the /callback route.

Create a callback-page.vue file under the src/pages directory:

COMMAND
touch src/pages/callback-page.vue

Populate src/pages/callback-page.vue with the following code:

src/pages/callback-page.vue
<template>
<div class="page-layout">
<NavBar />
<MobileNavBar />
<div class="page-layout__content">
<slot />
</div>
</div>
</template>
<script>
import NavBar from "@/components/navigation/desktop/nav-bar.vue";
import MobileNavBar from "@/components/navigation/mobile/mobile-nav-bar.vue";
export default {
components: {
NavBar,
MobileNavBar,
},
};
</script>

The callback-page.vue component will only render the navigation bar and an empty content container to help you create a smooth transition between a route with no content, /callback, to a route with content, such as the /profile page.

The next step is to integrate your callback-page.vue component with the Vue.js router.

Locate the src/router/index.js file, which defines your Vue.js router module, and update it like so:

src/router/index.js
import HomePage from "@/pages/home-page.vue";
import { createRouter, createWebHistory } from "vue-router";
const NotFoundPage = () => import("@/pages/not-found-page.vue");
const ProfilePage = () => import("@/pages/profile-page.vue");
const PublicPage = () => import("@/pages/public-page.vue");
const ProtectedPage = () => import("@/pages/protected-page.vue");
const AdminPage = () => import("@/pages/admin-page.vue");
const CallbackPage = () => import("@/pages/callback-page.vue");
const routes = [
{
path: "/",
name: "home",
component: HomePage,
},
{
path: "/profile",
name: "profile",
component: ProfilePage,
},
{
path: "/public",
name: "public",
component: PublicPage,
},
{
path: "/protected",
name: "protected",
component: ProtectedPage,
},
{
path: "/admin",
name: "admin",
component: AdminPage,
},
{
path: "/callback",
name: "callback",
component: CallbackPage,
},
{
path: "/:catchAll(.*)",
name: "Not Found",
component: NotFoundPage,
},
];
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
export default router;

What are the benefits of using a callback page?

Implementing a page that specializes in handling the user redirection from the Auth0 Universal Login Page to your application (the callback event) has some benefits:

  • Your users won't see any flashing of the home page component, which renders at the root path, /.
  • By showing the navigation bar in the /callback route, your user may feel that your Vue.js application loads fast.
  • By not showing the footer, your users may feel that your Vue.js application loads smoothly.
    • If you were to render the footer component, your application may appear to be jumpy as the footer may show up briefly but then it would be pushed down when the content above it loads.
  • You can avoid making unnecessary or costly API calls that may run when loading your home page components.

Once you add a login and logout button to this app, you can verify this user experience improvement by using your browser's developer tools. In the case of Google Chrome, you could do the following:

If you are not convinced yet, let's explore more details on the impact of this strategy.

Imagine that you want to redirect your users to the /profile after they log in. If you were to use the root URL of your Vue.js Options API application, http://localhost:4040, as the Auth0 Callback URL, you may hurt the user experience when the user's connection is slow or when you are lazy loading the /profile route:

  • This Vue.js application offers a /profile page that will display user profile information such as name and email address. However, this application also lazy loads that /profile route using the Vue.js Router.
  • Since user profile information is private, it must be protected against unauthorized access.
  • The Auth0 Vue SDK allows you to easily require users to log in before they can access a route.
  • When a user who is not logged in clicks on the /profile page navigation tab, Auth0 will redirect them to a page to log in.
  • Once your users log in, Auth0 will redirect them to your Vue.js application with some metadata that allows your application to redirect them to the protected page they intended to access.
  • When you use http://localhost:4040 as the Auth0 Callback URL, Auth0 will redirect your users to the home page first. Depending on how fast your application renders pages and handles redirects, your users may see the home page first before Vue.js takes them to the /profile page when the connection is slow or when you are lazy loading that route. This quick re-routing makes your user interface "flash", which makes the user interface feel janky or glitchy.
  • However, when you use http://localhost:4040/callback as the Auth0 Callback URL, Auth0 will take your users to a /callback route after they log in. You can then display a loading animation or nothing at all in that special route. Doing so makes the transition from /callback to /profile smoother as no unrelated or unexpected content shows up in the process.

Additionally, when you load the home page, /, you may trigger logic that fetches data from an external API or runs any other business logic related to hydrating the home page. If your intention is to show the users a /profile page after they log in, there's no need or value to run any of that home page business logic that won't impact the rendering of the /profile page. Instead, you may increase your operational costs by running unnecessary logic when any of your users log in. In that case, it's better to handle the Auth0 redirect in a minimal and performant specialized route, /callback.

Configure a Vue.js Authentication Plugin

It's important to note that the Auth0 Vue SDK is only compatible with Vue 3. It won't work with Vue.js v2 and below. Execute the following command to install the Auth0 Vue SDK:

COMMAND
npm install @auth0/auth0-vue

The Auth0 Vue SDK exposes the createAuth0() method that you can use to instantiate an Auth0 Vue.js plugin. You can connect that Auth0 plugin with your Vue.js application by passing the plugin instance to the app.use() method from Vue.

Update the src/main.js file as follows to execute the steps above:

src/main.js
import { createAuth0 } from "@auth0/auth0-vue";
import { createApp } from "vue";
import App from "./app.vue";
import "./assets/css/styles.css";
import router from "./router";
const app = createApp(App);
app
.use(router)
.use(
createAuth0({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
authorizationParams: {
redirect_uri: import.meta.env.VITE_AUTH0_CALLBACK_URL,
},
})
)
.mount("#root");

You define an instance of the authentication plugin from the Auth0 Vue SDK using the configuration values from the Auth0 application you created in the Auth0 Dashboard: Auth0 Domain and Client ID.

Additionally, you use the authorizationParams configuration object to define the query parameters that Vue needs to include on its calls to the Auth0 /authorize endpoint. You define the redirect_uri property within this object to specify the URL from your Vue.js application to where Auth0 should redirect your users after they successfully log in.

NOTE: 🚨 The order in which you register the Router and Auth0 Vue.js plugin with your Vue.js instance is important. You must register the Vue.js Router before the Auth0 Vue.js plugin, or you might experience unexpected behavior. 🚨.

When you use the Vue.js Options API, the functionality of the Auth0 plugin from the Auth0 Vue SDK will be available at a global level through the this.$auth0 object.

The Auth0 Vue SDK is a reactive wrapper around the Auth0 SPA SDK, making it easier to work with the asynchronous methods of the SDK in the context of a Vue.js application.

As such, all the configuration options for helper methods of the Auth0 SPA SDK also work with the helper methods of the Auth0 Vue SDK. You'll see examples of this compatibility when you create the Vue.js sign-up and logout buttons using the Options API in the following sections.

Auth0 and Vue.js connection set

You have completed setting up an authentication service that your Vue.js application can consume. All that is left is for you to continue building up the starter project throughout this guide by implementing components with the Vue.js Options API to trigger and manage the authentication flow.

Feel free to dive deeper into the Auth0 Documentation to learn more about how Auth0 helps you save time implementing and managing identity.

Add User Login to Vue.js

The steps on how to build a Vue.js login form or login page are complex. You can save development time by using a login page hosted by Auth0 that has a built-in login form that supports different types of user authentication: username and password, social login, and Multi-Factor Authentication (MFA). You just need to create a button that takes users from your Vue.js application to the login page.

Start by creating a buttons directory under the src/components directory:

COMMAND
mkdir src/components/buttons

Create a login-button.vue file under the src/components/buttons directory:

COMMAND
touch src/components/buttons/login-button.vue
Why are we using kebab-case and not PascalCase to create Vue.js component files, *.vue? According to the Vue.js Style Guide, "PascalCase works best with autocompletion in code editors, as it's consistent with how we reference components in JS(X) and templates, wherever possible. However, mixed case filenames can sometimes create issues on case-insensitive file systems, which is why kebab-case is also perfectly acceptable".

Populate src/components/buttons/login-button.vue like so:

src/components/buttons/login-button.vue
<template>
<button class="button__login" @click="handleLogin">Log In</button>
</template>
<script>
export default {
methods: {
handleLogin() {
this.$auth0.loginWithRedirect({
appState: {
target: "/profile",
},
});
},
},
};
</script>

As mentioned earlier, when you use the Vue.js Options API, you access the Auth0 plugin within your Vue.js components using the this.$auth0 reactive global object.

The this.$auth0.loginWithRedirect() method performs a redirect to the Auth0 /authorize endpoint to kickstart the authentication process. You can pass a configuration object to this method to customize the login experience.

By setting up the value of appState.target to /profile, you are telling the Auth0 Vue SDK the following: When my users log in with Auth0 and return to my Vue.js application, take them from the default callback URL path, /callback, to the "Profile" page, /profile. If you don't specify this appState.target option, your users will be redirected by default to the / path after they log in.

Add User Sign-Up to Vue.js

The process on how to build a Vue.js sign-up form is much more complex. However, you can use a sign-up form hosted by Auth0 that has a built-in password strength verification.

You can create a button that takes users from your Vue.js application to the sign-up page by specifying the screen_hint=signup property in the authorizationParams configuration object of the loginWithRedirect() method:

authorizationParams: {
screen_hint: "signup",
}

This loginWithRedirect() method is a wrapper from the Auth0 SPA SDK method of the same name. As such, you can use the RedirectLoginOptions document from the Auth0 SPA SDK to learn more details on these configuration options.

To see this in practice, create a signup-button.vue file under the src/components/buttons directory:

COMMAND
touch src/components/buttons/signup-button.vue

Populate src/components/buttons/signup-button.vue like so to define a sign-up button component:

src/components/buttons/signup-button.vue
<template>
<button class="button__sign-up" @click="handleSignUp">Sign Up</button>
</template>
<script>
export default {
methods: {
handleSignUp() {
this.$auth0.loginWithRedirect({
appState: {
target: "/profile",
},
authorizationParams: {
screen_hint: "signup",
},
});
},
},
};
</script>

Using the Auth0 Signup feature requires you to enable the Auth0 New Universal Login Experience in your tenant.

Open the Universal Login section of the Auth0 Dashboard and choose the "New" option under the "Experience" subsection.

Auth0 Universal Login Experience options

Scroll down and click on the "Save Changes" button.

The difference between the login and sign-up user experience will be more evident once you integrate those components with your Vue.js application and see them in action. You'll do that in the following sections.

Add User Logout to Vue.js

You can log out users from your Vue.js application by logging them out of their Auth0 sessions using the logout() method from the Auth0 Vue SDK.

Create a logout-button.vue file under the src/components/buttons directory:

COMMAND
touch src/components/buttons/logout-button.vue

Populate src/components/buttons/logout-button.vue like so:

src/components/buttons/logout-button.vue
<template>
<button class="button__logout" @click="handleLogout">Log Out</button>
</template>
<script>
export default {
methods: {
handleLogout() {
this.$auth0.logout({
logoutParams: {
returnTo: window.location.origin,
},
});
},
},
};
</script>

When using the this.$auth0.logout() method, the Auth0 Vue SDK clears the application session and redirects to the Auth0 /v2/logout endpoint to clear the Auth0 session under the hood.

As with the login method, you can pass an object argument to logout() to customize the logout behavior of the Vue.js application. You can define a logoutParams property on that configuration object to define parameters for the /v2/logout call. This process is fairly invisible to the user. See logoutParams for more details on the parameters available.

Here, you pass the logoutParams.returnTo option to specify the URL where Auth0 should redirect your users after they log out. Right now, you are working locally, and your Auth0 application's "Allowed Logout URLs" points to http://localhost:4040.

However, if you were to deploy your Vue.js application to production, you need to add the production logout URL to the "Allowed Logout URLs" list and ensure that Auth0 redirects your users to that production URL and not localhost. Setting logoutParams.returnTo to window.location.origin will do just that.

A best practice when working with Auth0 is to have different tenants for your different project environments. For example, it's recommended for developers to specify a production tenant. A production tenant gets higher rate limits than non-production tenants. Check out the "Set Up Multiple Environments" Auth0 document to learn more about how to set up development, staging, and production environments in the Auth0 Identity Platform.

Render Vue.js Components Based on Authentication

In this section, you'll learn how to render Vue.js components conditionally based on the status of the Auth0 Vue SDK or the authentication status of your users.

Render the authentication buttons conditionally

The Vue.js starter application features a desktop and mobile navigation experience.

When using your Vue.js application on a viewport large enough to fix a desktop or tablet experience, you'll see a navigation bar at the top of the page.

When using a viewport that fits the screen constraints of a mobile device, you'll see a menu button at the top-right corner of the page. Tapping or clicking on the menu button opens a modal that shows you the different pages that you can access in the application.

In this section, you'll expose the button components that trigger login, sign-up, and logout events through these page navigation elements.

Let's start with the desktop navigation user experience. You'll show both the login and sign-up buttons on the navigation bar when the user is not logged in. Naturally, you'll show the logout button when the user is logged in.

Update src/components/navigation/desktop/nav-bar-buttons.vue as follows to implement the user experience defined above:

src/components/navigation/desktop/nav-bar-buttons.vue
<template>
<div class="nav-bar__buttons">
<template v-if="!isAuthenticated">
<SignupButton />
<LoginButton />
</template>
<template v-if="isAuthenticated">
<LogoutButton />
</template>
</div>
</template>
<script>
import LoginButton from "@/components/buttons/login-button.vue";
import LogoutButton from "@/components/buttons/logout-button.vue";
import SignupButton from "@/components/buttons/signup-button.vue";
export default {
components: { LoginButton, LogoutButton, SignupButton },
data() {
return {
isAuthenticated: this.$auth0.isAuthenticated,
};
},
};
</script>

The this.$auth0.isAuthenticated value reflects the authentication state of your users as tracked by the Auth0 Vue SDK plugin. This value is true when the user has been authenticated and false when not. As such, you can use the this.$auth0.isAuthenticated value to render UI elements conditionally depending on the authentication state of your users, as you did above.

The mobile navigation experience works in the same fashion, except that the authentication-related buttons are tucked into the mobile menu modal.

Update src/components/navigation/mobile/mobile-nav-bar-buttons.vue as follows:

src/components/navigation/mobile/mobile-nav-bar-buttons.vue
<template>
<div class="mobile-nav-bar__buttons">
<template v-if="!isAuthenticated">
<SignupButton />
<LoginButton />
</template>
<template v-if="isAuthenticated">
<LogoutButton />
</template>
</div>
</template>
<script>
import LoginButton from "@/components/buttons/login-button.vue";
import LogoutButton from "@/components/buttons/logout-button.vue";
import SignupButton from "@/components/buttons/signup-button.vue";
export default {
components: { LoginButton, LogoutButton, SignupButton },
data() {
return {
isAuthenticated: this.$auth0.isAuthenticated,
};
},
};
</script>

Go ahead and try to log in. Your Vue.js application redirects you to the Auth0 Universal Login page. You can use the form to log in with a username and password or a social identity provider like Google. Notice that this login page also gives you the option to sign up.

New Auth0 Universal Login Experience Form

However, when you click the sign-up button from your application directly, Vue.js takes you to the Signup page, where your users can sign up for the Vue.js application. Try it out!

New Auth0 Universal Login Experience Signup Page
You can customize the appearance of New Universal Login pages. You can also override any text in the New Experience using the Text Customization API.

Notice that when you finish logging in or signing up, Auth0 redirects you to your Vue.js app, but the login and sign-up buttons may briefly show up before the logout button renders. You'll fix that next.

Render the application conditionally

The user interface flashes because your Vue.js app doesn't know if Auth0 has authenticated the user yet. Your Vue.js application will know the user authentication status after the Auth0 Vue SDK initializes.

To fix that UI flashing, use the this.$auth0.isLoading value to render the app.vue component once the Auth0 Vue SDK has finished loading.

Open src/app.vue and update it as follows:

src/app.vue
<template>
<div v-if="isLoading" class="page-layout">
<PageLoader />
</div>
<router-view v-else />
</template>
<script>
import PageLoader from "@/components/page-loader.vue";
export default {
components: {
PageLoader,
},
data() {
return {
isLoading: this.$auth0.isLoading,
};
},
};
</script>

While the SDK is loading, the page-loader.vue component renders, which shows up an animation. Log out and log back in to see this in action. No more UI flashing should happen.

Render navigation tabs conditionally

There may be use cases where you want to hide user interface elements from users who have not logged in to your application. For this starter application, only authenticated users should see the navigation tabs to access the /protected and /admin pages.

To implement this use case, you'll rely on the this.$auth0.isAuthenticated value once again.

Open the src/components/navigation/desktop/nav-bar-tabs.vue component file that defines your desktop navigation tabs and update it like so:

src/components/navigation/desktop/nav-bar-tabs.vue
<template>
<div class="nav-bar__tabs">
<NavBarTab path="/profile" label="Profile" />
<NavBarTab path="/public" label="Public" />
<template v-if="isAuthenticated">
<NavBarTab path="/protected" label="Protected" />
<NavBarTab path="/admin" label="Admin" />
</template>
</div>
</template>
<script>
import NavBarTab from "@/components/navigation/desktop/nav-bar-tab.vue";
export default {
components: {
NavBarTab,
},
data() {
return {
isAuthenticated: this.$auth0.isAuthenticated,
};
},
};
</script>

Next, open the src/components/navigation/mobile/mobile-nav-bar-tabs.vue component file that defines your mobile navigation tabs and update it like so:

src/components/navigation/mobile/mobile-nav-bar-tabs.vue
<template>
<div class="mobile-nav-bar__tabs">
<MobileNavBarTab path="/profile" label="Profile" />
<MobileNavBarTab path="/public" label="Public" />
<template v-if="isAuthenticated">
<MobileNavBarTab path="/protected" label="Protected" />
<MobileNavBarTab path="/admin" label="Admin" />
</template>
</div>
</template>
<script>
import MobileNavBarTab from "@/components/navigation/mobile/mobile-nav-bar-tab.vue";
export default {
components: { MobileNavBarTab },
data() {
return {
isAuthenticated: this.$auth0.isAuthenticated,
};
},
};
</script>

Log out from your Vue.js application and notice how now you can only see the tabs for the /profile and /public pages in the navigation bar, along with the login and sign-up buttons. Log in and then see the rest of the navigation bar show up.

Keep in mind that this does not restrict access to the /admin and /protected pages at all. You'll learn how to use the Auth0 Vue SDK to protect Vue.js routes in the next section.

Add Route Guards to Vue.js

You can create an authentication route guard to protect Vue.js routes. Vue.js will ask users who visit the protected route to log in if they haven't already. Once they log in, Vue.js takes them to the route they were trying to access.

You can apply a guard to any route defined in the Vue.js router module by updating src/router/index.js as follows:

src/router/index.js
import HomePage from "@/pages/home-page.vue";
import { authGuard } from "@auth0/auth0-vue";
import { createRouter, createWebHistory } from "vue-router";
const NotFoundPage = () => import("@/pages/not-found-page.vue");
const ProfilePage = () => import("@/pages/profile-page.vue");
const PublicPage = () => import("@/pages/public-page.vue");
const ProtectedPage = () => import("@/pages/protected-page.vue");
const AdminPage = () => import("@/pages/admin-page.vue");
const CallbackPage = () => import("@/pages/callback-page.vue");
const routes = [
{
path: "/",
name: "home",
component: HomePage,
},
{
path: "/profile",
name: "profile",
component: ProfilePage,
beforeEnter: authGuard,
},
{
path: "/public",
name: "public",
component: PublicPage,
},
{
path: "/protected",
name: "protected",
component: ProtectedPage,
beforeEnter: authGuard,
},
{
path: "/admin",
name: "admin",
component: AdminPage,
beforeEnter: authGuard,
},
{
path: "/callback",
name: "callback",
component: CallbackPage,
},
{
path: "/:catchAll(.*)",
name: "Not Found",
component: NotFoundPage,
},
];
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
export default router;

You use the authGuard from the Auth0 Vue SDK to protect the /profile, /protected, and /admin routes by adding it as the value of the beforeEnter route configuration property. Since beforeEnter is a pre-route guard, Vue.js will run authGuard before accessing that route and rendering any of its components.

If the conditions defined by authGuard pass, the component renders. Otherwise, authGuard instructs Vue.js to take you to the Auth0 Universal Login Page to authenticate.

You can now test that these guarded paths require users to log in before accessing them. Log out and try to access the Profile page, Protected page, or the Admin page. If it works, Vue.js redirects you to log in with Auth0.

Once you log in, Vue.js should take you to the /profile page as specified by the appState.target property present in the login button component definition.

Client-side guards improve the user experience of your Vue.js application, not its security.

In Security StackExchange, Conor Mancone explains that server-side guards are about protecting data while client-side guards are about improving user experience.

The main takeaways from his response are:

  • You can't rely on client-side restrictions, such as navigation guards and protected routes, to protect sensitive information.
    • Attackers can potentially get around client-side restrictions.
  • Your server should not return any data that a user should not access. The wrong approach is to return all the user data from the server and let the front-end framework decide what to display and what to hide based on the user authentication status.
    • Anyone can open the browser's developer tools and inspect the network requests to view all the data.
  • The use of navigation guards helps improve user experience, not user security.
    • Without guards, a user who has not logged in may wander into a page with restricted information and see an error like "Access Denied".
    • With guards that match the server permissions, you can prevent users from seeing errors by preventing them from visiting the restricted page.

Get User Profile Information in Vue.js

After a user successfully logs in, Auth0 sends an ID token to your Vue.js application. Authentication systems, such as Auth0, use ID Tokens in token-based authentication to cache user profile information and provide it to a client application. The caching of ID tokens can improve performance and responsiveness for your Vue.js application.

You can use the data from the ID token to personalize the user interface of your Vue.js application. The Auth0 Vue SDK decodes the ID token and stores its data in the this.$auth0.user object. Some of the ID token information includes the name, nickname, picture, and email of the logged-in user.

How can you use the ID token to create a profile page for your users?

Update src/pages/profile-page.vue as follows:

src/pages/profile-page.vue
<template>
<PageLayout>
<div class="content-layout">
<h1 id="page-title" class="content__title">Profile Page</h1>
<div class="content__body">
<p id="page-description">
<span
>You can use the <strong>ID Token</strong> to get the profile
information of an authenticated user.</span
>
<span
><strong
>Only authenticated users can access this page.</strong
></span
>
</p>
<div class="profile-grid">
<div class="profile__header">
<img :src="user.picture" alt="Profile" class="profile__avatar" />
<div class="profile__headline">
<h2 class="profile__title">{{ user.name }}</h2>
<span class="profile__description">{{ user.email }}</span>
</div>
</div>
<div class="profile__details">
<CodeSnippet title="Decoded ID Token" :code="code" />
</div>
</div>
</div>
</div>
</PageLayout>
</template>
<script>
import CodeSnippet from "@/components/code-snippet.vue";
import PageLayout from "@/components/page-layout.vue";
export default {
components: {
PageLayout,
CodeSnippet,
},
data() {
return {
user: this.$auth0.user,
};
},
computed: {
code() {
return JSON.stringify(this.user, null, 2);
},
},
};
</script>

What's happening within the profile-page.vue component?

  • You display three properties from the this.$auth0.user object in the user interface: name, picture, and email.

  • Since the data comes from a simple object, you don't have to fetch it using any asynchronous calls.

  • Finally, you display the full content of the decoded ID token within a code box. You can now see all the other properties available for you to use. The properties are known as "token claims".

The profile-page.vue component renders user information that you could consider private or sensitive. Additionally, the user property is null if there is no logged-in user. So either way, this component should only render if Auth0 has authenticated the user. You are already restricting access to this page component by using the authGuard in the /profile route definition of your Vue.js router module, src/router/index.js.

If you are logged in to your application, visit http://localhost:4040/profile to see your user profile details.

Authentication Beyond Passwords: Try Passkeys Today

So far, you have seen how a user can sign up or log in to your application with a username and password. However, you can free your users from having to remember yet another password by allowing them to use passkeys as a new way to log in.

Passkeys are a phishing-resistant alternative to traditional authentication factors, such as the username/password combo, that offer an easier and more secure login experience to users.

You don't have to write any new code to start using passkeys in your application. You can follow the "Authentication with Passkeys" lab to learn how to enable passkeys in your Auth0 tenant and learn more about this emerging technology. Once you complete that optional lab, you can come back to this guide to continue learning about how to access protected API resources on behalf of a user from your application.

A form modal giving you information on how a passkey works and the option to create a passkey

Integrate Vue.js with an API Server

This section focuses on showing you how to get an access token in your Vue.js application and how to use it to make API calls to protected API endpoints.

When you use Auth0, you delegate the authentication process to a centralized service. Auth0 provides you with functionality to log in and log out users from your Vue.js application. However, your application may need to access protected resources from an API.

You can also protect an API with Auth0. There are multiple API quickstarts to help you integrate Auth0 with your backend platform.

When you use Auth0 to protect your API, you also delegate the authorization process to a centralized service that ensures only approved client applications can access protected resources on behalf of a user.

How can you make secure API calls from Vue.js?

Your Vue.js application authenticates the user and receives an access token from Auth0. The application can then pass that access token to your API as a credential. In turn, your API can use Auth0 libraries to verify the access token it receives from the calling application and issue a response with the desired data.

Instead of creating an API from scratch to test the authentication and authorization flow between the client and the server, you can pair this client application with an API server that matches the technology stack you use at work. The Vue.js "Hello World" client application that you have been building up can interact with any of the "Hello World" API server samples from the Auth0 Developer Center.

The "Hello World" API server samples run on http://localhost:6060 by default, which is the same origin URL and port where the mocked JSON server is running. As such, before you set up the "Hello World" API server, locate the tab where you are running the npm run api command and stop the mocked JSON server process.

Pick an API code sample in your preferred backend framework and language from the list below and follow the instructions on the code sample page to set it up. Once you complete the sample API server setup, please return to this page to learn how to integrate that API server with your Vue.js application.

actix-web
rust
Actix Web/Rust API:Authorization Code Sample
Code sample of a simple Actix Web server that implements token-based authorization using Auth0.
aspnet-core
csharp
ASP.NET Core Code Sample:Web API Authorization
Code sample of a simple ASP.NET Core server that implements token-based authorization using Auth0.
aspnet-core
csharp
ASP.NET Core v5 Code Sample:Web API Authorization
Code sample of a simple ASP.NET Core v5.0 server that implements token-based authorization using Auth0.
django
python
Django/Python API:Authorization Code Sample
Code sample of a simple Django server that implements token-based authorization using Auth0.
express
javascript
Express.js Code Sample:Basic API Authorization
Code sample of a simple Express.js server that implements token-based authorization using Auth0.
express
typescript
Express.js/TypeScript Code Sample:Basic API Authorization
Code sample of a simple Express.js server built with TypeScript that implements token-based authorization using Auth0.
fastapi
python
FastAPI/Python Code Sample:Basic API Authorization
Code sample of a simple FastAPI server that implements token-based authorization using Auth0.
flask
python
Flask/Python API:Authorization Code Sample
Code sample of a simple Flask server that implements token-based authorization using Auth0.
laravel
php
Laravel/PHP Code Sample:Basic API Authorization with Auth0 Laravel SDK
Code sample of a simple Laravel server that implements token-based authorization using the Auth0 Laravel SDK.
laravel
php
Laravel/PHP Code Sample:Basic API Authorization with Auth0 PHP SDK
Code sample of a simple Laravel server that implements token-based authorization using the Auth0 PHP SDK.
lumen
php
Lumen Code Sample:Basic API Authorization
Code sample of a simple Lumen server that implements token-based authorization using Auth0.
nestjs
typescript
NestJS Code Sample:Basic API Authorization
Code sample of a simple NestJS server that implements token-based authorization using Auth0.
phoenix
elixir
Phoenix/Elixir API:Authorization Code Sample
Code sample of a simple Phoenix server that implements token-based authorization using Auth0.
rails
ruby
Ruby on Rails API:Authorization Code Sample
Code sample of a simple Rails server that implements authorization using Auth0.
spring
java
Spring Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, using Spring Security and the Okta Spring Boot Starter.
spring
java
Spring Functional Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, following a functional approach.
spring-webflux
java
Spring WebFlux Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring WebFlux API server to protect API endpoints, using Spring Security and the Okta Spring Boot Starter.
standard-library
golang
Golang Code Sample:Basic API Authorization
Code sample of a simple Golang server that implements token-based authorization using Auth0.
symfony
php
Symfony Code Sample:Basic API Authorization
Code sample of a simple Symfony server that implements token-based authorization using Auth0.

Call a Protected API from Vue.js

Once you have set up the API server code sample, you should have created an Auth0 Audience value. Store that value in the following field so that you can use it throughout the instructions presented on this page easily:

Now, update the .env file under the Vue.js project directory as follows:

.env
VITE_API_SERVER_URL=http://localhost:6060
VITE_AUTH0_DOMAIN=AUTH0-DOMAIN
VITE_AUTH0_CLIENT_ID=AUTH0-CLIENT-ID
VITE_AUTH0_CALLBACK_URL=http://localhost:4040/callback
VITE_AUTH0_AUDIENCE=AUTH0-AUDIENCE

You are using VITE_AUTH0_AUDIENCE to add the value of your Auth0 API Audience so that your Vue.js client application can request resources from the API that such audience value represents.

Let's understand better what the VITE_AUTH0_AUDIENCE and VITE_API_SERVER_URL values represent.

The VITE_API_SERVER_URL is simply the URL where your sample API server listens for requests. In production, you'll change this value to the URL of your live server.

Your Vue.js application must pass an access token when it calls a target API to access protected resources. You can request an access token in a format that the API can verify by passing the audience to the Auth0 Vue SDK.

The value of the Auth0 Audience must be the same for both the Vue.js client application and the API server you decided to set up.

Why is the Auth0 Audience value the same for both apps? Auth0 uses the value of the audience prop to determine which resource server (API) the user is authorizing your Vue.js application to access. It's like a phone number. You want to ensure that your Vue.js application "texts the right API".

As such, update the src/main.js file from your Vue.js project as follows to add the audience value:

src/main.js
import { createAuth0 } from "@auth0/auth0-vue";
import { createApp } from "vue";
import App from "./app.vue";
import "./assets/css/styles.css";
import router from "./router";
const app = createApp(App);
app
.use(router)
.use(
createAuth0({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
authorizationParams: {
audience: import.meta.env.VITE_AUTH0_AUDIENCE,
redirect_uri: import.meta.env.VITE_AUTH0_CALLBACK_URL,
},
})
)
.mount("#root");

You are now including an audience property in the authorizationParams configuration object you pass to the createAuth0() method. Recall that the createAuth0() method creates an instance of the Auth0 plugin, which allows you to access the Auth0 Vue SDK methods globally in your Vue.js application through the this.$auth0 object when using the Options API.

What about using scopes?

A property that you are not configuring directly in the createAuth0() method is the scope property. When you don't pass a scope option to Auth0 Vue SDK, which powers Auth0Plugin, the SDK defaults to using the OpenID Connect Scopes: openid profile email.

  • openid: This scope informs the Auth0 Authorization Server that the Client is making an OpenID Connect (OIDC) request to verify the user's identity. OpenID Connect is an authentication protocol.

  • profile: This scope value requests access to the user's default profile information, such as name, nickname, and picture.

  • email: This scope value requests access to the email and email_verified information.

The details of the OpenID Connect Scopes go into the ID Token. However, you can define custom API scopes to implement access control. You'll identify those custom scopes in the calls that your client applications make to that API. Auth0 includes API scopes in the access token as the scope claim value.

The concepts about API scopes or permissions are better covered in an Auth0 API tutorial such as "Use TypeScript to Create a Secure API with Node.js and Express: Role-Based Access Control".

The Auth0 Vue SDK provides you with a method to get an access token from Auth0: getAccessTokenSilently(). If you already have an access token stored in memory, but the token is invalid or expired, this method will get you a new one. Usually, getting new access tokens requires the user to log in again. However, The Auth0 Vue SDK lets you get one in the background without interrupting the user. As the name implies, it's a method to getTokenSilently()... 🤫😶

It's now time to update the /protected and /admin pages to let users retrieve private data from the API server. Please ensure that your sample API server is running as you complete the following steps.

Start by updating the service methods present in the src/services/message.service.js file as follows:

src/services/message.service.js
import { callExternalApi } from "./external-api.service";
const apiServerUrl = import.meta.env.VITE_API_SERVER_URL;
export const getPublicResource = async () => {
const config = {
url: `${apiServerUrl}/api/messages/public`,
method: "GET",
headers: {
"content-type": "application/json",
},
};
const { data, error } = await callExternalApi({ config });
return {
data: data || null,
error,
};
};
export const getProtectedResource = async (accessToken) => {
const config = {
url: `${apiServerUrl}/api/messages/protected`,
method: "GET",
headers: {
"content-type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
};
const { data, error } = await callExternalApi({ config });
return {
data: data || null,
error,
};
};
export const getAdminResource = async (accessToken) => {
const config = {
url: `${apiServerUrl}/api/messages/admin`,
method: "GET",
headers: {
"content-type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
};
const { data, error } = await callExternalApi({ config });
return {
data: data || null,
error,
};
};

You are changing the signature of the getProtectedResource() and getAdminResource() methods to include an accessToken parameter.

You then pass that accessToken value as a bearer credential in the authorization header of the request config object. You make requests from your Vue.js application using the callExternalApi() helper method defined in the src/services/external-api.service.js module. callExternalApi() uses axios to make its API calls.

With the message service methods in place, proceed to update the src/pages/protected-page.vue component as follows:

src/pages/protected-page.vue
<template>
<PageLayout>
<div class="content-layout">
<h1 id="page-title" class="content__title">Protected Page</h1>
<div class="content__body">
<p id="page-description">
<span
>This page retrieves a <strong>protected message</strong> from an
external API.</span
>
<span
><strong
>Only authenticated users can access this page.</strong
></span
>
</p>
<CodeSnippet title="Protected Message" :code="message" />
</div>
</div>
</PageLayout>
</template>
<script>
import CodeSnippet from "@/components/code-snippet.vue";
import PageLayout from "@/components/page-layout.vue";
import { getProtectedResource } from "@/services/message.service";
export default {
components: {
PageLayout,
CodeSnippet,
},
data() {
return {
message: "",
};
},
async mounted() {
const accessToken = await this.$auth0.getAccessTokenSilently();
const { data, error } = await getProtectedResource(accessToken);
if (data) {
this.message = JSON.stringify(data, null, 2);
}
if (error) {
this.message = JSON.stringify(error, null, 2);
}
},
};
</script>

What is happening now within the protected-page.vue component?

  • You use the mounted Options API lifecycle method to request data from your API server to hydrate your page.

  • You call the async this.$auth0.getAccessTokenSilently() method to fetch a new access token from the Auth0 Authorization Server. Under the hood, the Auth0 Vue SDK triggers a call to the Auth0 /oauth/token endpoint.

    • Your previous login request did not include an audience parameter. As such, the Auth0 Vue SDK doesn't have an access token stored in memory, and it requests a new one.
    • The SDK will now store that access token in memory. For future getAccessTokenSilently() calls, the SDK will use the stored access token and only request a new one when the stored access token expires.
  • You then use the getProtectedResource() service method to fetch the protected message from your API server.

    • You pass the access token that you fetched to this service method.
    • In turn, getProtectedResource() passes that access token as a bearer credential in the authorization header of the request it makes to your API server.
  • Finally, if you retrieve the data from the server correctly, you'll display that message data in the message box. Otherwise, you'll show the corresponding error message.

Log out from your Vue.js application and log back in to get a new access token from Auth0 that includes the audience information.

Visit the http://localhost:4040/protected page and verify that you now get a valid response from the server.

Now, update the src/pages/admin-page.vue component to implement the same business logic outlined before but this time using the getAdminResource() service method to retrieve the correct message:

src/pages/admin-page.vue
<template>
<PageLayout>
<div class="content-layout">
<h1 id="page-title" class="content__title">Admin Page</h1>
<div class="content__body">
<p id="page-description">
<span
>This page retrieves an <strong>admin message</strong> from an
external API.</span
>
<span
><strong
>Only authenticated users with the
<code>read:admin-messages</code> permission should access this
page.</strong
></span
>
</p>
<CodeSnippet title="Admin Message" :code="message" />
</div>
</div>
</PageLayout>
</template>
<script>
import CodeSnippet from "@/components/code-snippet.vue";
import PageLayout from "@/components/page-layout.vue";
import { getAdminResource } from "@/services/message.service";
export default {
components: {
CodeSnippet,
PageLayout,
},
data() {
return {
message: "",
};
},
async mounted() {
const accessToken = await this.$auth0.getAccessTokenSilently();
const { data, error } = await getAdminResource(accessToken);
if (data) {
this.message = JSON.stringify(data, null, 2);
}
if (error) {
this.message = JSON.stringify(error, null, 2);
}
},
};
</script>

That's all it takes to integrate Vue.js with an external API server that is also secured by Auth0 and to use an access token to consume protected server resources from your Vue.js client application.

Next Steps

You have implemented user authentication in Vue.js to identify your users, get user profile information, and control the content that your users can access by protecting routes and API resources.

This guide covered the most common authentication use case for a Vue.js application: simple login and logout. However, Auth0 is an extensible and flexible identity platform that can help you achieve even more. If you have a more complex use case, check out the Auth0 Architecture Scenarios to learn more about the typical architecture scenarios we have identified when working with customers on implementing Auth0.

We'll cover advanced authentication patterns and tooling in future guides, such as using a pop-up instead of redirecting users to log in, adding permissions to ID tokens, using metadata to enhance user profiles, and much more.