Published: March 08 2019

Vue.js - Role Based Authorization Tutorial with Example

Tutorial built with Vue 2.6.8 and Webpack 4.29

Other versions available:

In this tutorial we'll go through an example of how you can implement role based authorization / access control in Vue.js. The example builds on another tutorial I posted recently which focuses on JWT authentication in Vue + Vuex, in this version I've removed Vuex to show how you can build a Vue.js app without Vuex, and extended the example to include role based authorization / access control on top of the JWT authentication.

The tutorial example is pretty minimal and contains just 3 pages to demonstrate role based authorization in Vue - a login page, a home page and an admin page. The example contains two users - a Normal User who has access to the home page, and an Admin User who has access to everything (home page and admin page).

The project is available on GitHub at https://github.com/cornflourblue/vue-role-based-authorization-example.

Here it is in action: (See on CodeSandbox at https://codesandbox.io/s/k5kp135z95)


Running the Vue.js Role Based Authorization Example Locally

The tutorial example uses Webpack 4 to transpile the Vue.js code and bundle the modules together, and the webpack dev server is used as the local web server, to learn more about using webpack you can check out the official webpack docs.

  1. Install NodeJS and NPM from https://nodejs.org/en/download/.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/vue-role-based-authorization-example
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the command line in the project root folder.
  5. Your browser should automatically open at http://localhost:8080 with the login page of the demo Vue.js role-based authorization app displayed.

For more info on setting up a Vue.js development environment see Vue - Setup Development Environment.


Running the Tutorial Example with a Real Backend API

The Vue.js role based access control example app uses a fake / mock backend by default so it can run in the browser without a real api, to switch to a real backend api you just have to remove or comment out the 2 lines below the comment // setup fake backend located in the /src/index.js file.

You can build your own backend api or start with one of the below options:


Vue.js Role Based Access Control Project Structure

All source code for the Vue.js role based authorization tutorial is located in the /src folder. Inside the src folder there is a folder per feature (app, admin, home, login) and a couple of folders for non-feature code that can be shared across different parts of the app (_helpers, _services).

I prefixed non-feature folders with an underscore "_" to group them together and make it easy to distinguish between features and non-features, it also keeps the project folder structure shallow so it's quick to see everything at a glance from the top level and to navigate around the project.

The index.js files in the shared/non-feature folders are barrel files that group the exported modules from a folder together so they can be imported using the folder path instead of the full module path and to enable importing multiple modules in a single import (e.g. import { userService, authenticationService } from '@/_services').

A path alias '@' has been configured in the webpack.config.js that maps to the '/src' directory. This allows imports to be relative to the '/src' folder by prefixing the import path with '@', removing the need to use long relative paths like import MyComponent from '../../../MyComponent'.

Click any of the below links to jump down to a description of each file along with it's code:

 

Vue.js Tutorial Helpers Folder

Path: /src/_helpers

The helpers folder contains all the bits and pieces that don't fit into other folders but don't justify having a folder of their own.

 

Vue.js Tutorial Fake / Mock Backend

Path: /src/_helpers/fake-backend.js

The fake backend enables the example to run without a backend (backend-less), it contains a hardcoded collection of users and provides fake implementations for the api endpoints "authenticate", "get user by id", and "get all users", these would be handled by a real api and database in a production application.

The "authenticate" endpoint is used for logging in to the application and is publicly accessible, the "get user by id" is restricted to authenticated users in any role, however regular users can only access their own user record whereas admin users can access any user record. The "get all users" endpoint is restricted to admin users only.

The fake backend is implemented by monkey patching the fetch() function to intercept certain api requests and mimic the behaviour of a real api. Any requests that aren't intercepted get passed through to the real fetch() function.

import { Role } from './'

export function configureFakeBackend() {
    let users = [
        { id: 1, username: 'admin', password: 'admin', firstName: 'Admin', lastName: 'User', role: Role.Admin },
        { id: 2, username: 'user', password: 'user', firstName: 'Normal', lastName: 'User', role: Role.User }
    ];
    let realFetch = window.fetch;
    window.fetch = function (url, opts) {
        const authHeader = opts.headers['Authorization'];
        const isLoggedIn = authHeader && authHeader.startsWith('Bearer fake-jwt-token');
        const roleString = isLoggedIn && authHeader.split('.')[1];
        const role = roleString ? Role[roleString] : null;

        return new Promise((resolve, reject) => {
            // wrap in timeout to simulate server api call
            setTimeout(() => {
                // authenticate - public
                if (url.endsWith('/users/authenticate') && opts.method === 'POST') {
                    const params = JSON.parse(opts.body);
                    const user = users.find(x => x.username === params.username && x.password === params.password);
                    if (!user) return error('Username or password is incorrect');
                    return ok({
                        id: user.id,
                        username: user.username,
                        firstName: user.firstName,
                        lastName: user.lastName,
                        role: user.role,
                        token: `fake-jwt-token.${user.role}`
                    });
                }

                // get user by id - admin or user (user can only access their own record)
                if (url.match(/\/users\/\d+$/) && opts.method === 'GET') {
                    if (!isLoggedIn) return unauthorised();

                    // get id from request url
                    let urlParts = url.split('/');
                    let id = parseInt(urlParts[urlParts.length - 1]);

                    // only allow normal users access to their own record
                    const currentUser = users.find(x => x.role === role);
                    if (id !== currentUser.id && role !== Role.Admin) return unauthorised();

                    const user = users.find(x => x.id === id);
                    return ok(user);
                }

                // get all users - admin only
                if (url.endsWith('/users') && opts.method === 'GET') {
                    if (role !== Role.Admin) return unauthorised();
                    return ok(users);
                }

                // pass through any requests not handled above
                realFetch(url, opts).then(response => resolve(response));

                // private helper functions

                function ok(body) {
                    resolve({ ok: true, text: () => Promise.resolve(JSON.stringify(body)) })
                }

                function unauthorised() {
                    resolve({ status: 401, text: () => Promise.resolve(JSON.stringify({ message: 'Unauthorised' })) })
                }

                function error(message) {
                    resolve({ status: 400, text: () => Promise.resolve(JSON.stringify({ message })) })
                }
            }, 500);
        });
    }
}
 

Vue.js Tutorial Handle Response

Path: /src/_helpers/handle-response.js

The handleResponse function checks responses from the api to see if the request was unauthorised, forbidden or unsuccessful.

If the response status is 401 Unauthorized or 403 Forbidden then the user is automatically logged out of the application, this handles if the user token is no longer valid for any reason. If the response contains an error then a rejected promise is returned that includes the error message, otherwise if the request was successful then the response data is returned as a JSON object.

import { authenticationService } from '@/_services';

export function handleResponse(response) {
    return response.text().then(text => {
        const data = text && JSON.parse(text);
        if (!response.ok) {
            if ([401, 403].indexOf(response.status) !== -1) {
                // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
                authenticationService.logout();
                location.reload(true);
            }

            const error = (data && data.message) || response.statusText;
            return Promise.reject(error);
        }

        return data;
    });
}
 

Vue.js Tutorial Request Options

Path: /src/_helpers/request-options.js

The request options object contains helper methods for generating common http headers required for different request types. It is used by the authentication service and user service for making requests to the api.

import { authenticationService } from '@/_services';

export const requestOptions = {
    get() {
        return {
            method: 'GET',
            ...headers()
        };
    },
    post(body) {
        return {
            method: 'POST',
            ...headers(),
            body: JSON.stringify(body)
        };
    },
    patch(body) {
        return {
            method: 'PATCH',
            ...headers(),
            body: JSON.stringify(body)
        };
    },
    put(body) {
        return {
            method: 'PUT',
            ...headers(),
            body: JSON.stringify(body)
        };
    },
    delete() {
        return {
            method: 'DELETE',
            ...headers()
        };
    }
}

function headers() {
    const currentUser = authenticationService.currentUserValue || {};
    const authHeader = currentUser.token ? { 'Authorization': 'Bearer ' + currentUser.token } : {}
    return {
        headers: {
            ...authHeader,
            'Content-Type': 'application/json'
        }
    }
}
 

Vue.js Tutorial Role Object / Enum

Path: /src/_helpers/role.js

The role object defines the all the roles in the example application, I created it to use like an enum to avoid passing roles around as strings, so instead of 'Admin' we can use Role.Admin.

export const Role = {
    Admin: 'Admin',
    User: 'User'
}
 

Vue.js Tutorial Router

Path: /src/_helpers/router.js

The router defines all of the routes of the example Vue.js application, and enforces authorization to restricted routes inside the router.beforeEach() event hook.

import Vue from 'vue';
import Router from 'vue-router';

import { authenticationService } from '@/_services';
import { Role } from '@/_helpers';
import HomePage from '@/home/HomePage';
import AdminPage from '@/admin/AdminPage';
import LoginPage from '@/login/LoginPage';

Vue.use(Router);

export const router = new Router({
    mode: 'history',
    routes: [
        { 
            path: '/', 
            component: HomePage, 
            meta: { authorize: [] } 
        },
        { 
            path: '/admin', 
            component: AdminPage, 
            meta: { authorize: [Role.Admin] } 
        },
        { 
            path: '/login', 
            component: LoginPage 
        },

        // otherwise redirect to home
        { path: '*', redirect: '/' }
    ]
});

router.beforeEach((to, from, next) => {
    // redirect to login page if not logged in and trying to access a restricted page
    const { authorize } = to.meta;
    const currentUser = authenticationService.currentUserValue;

    if (authorize) {
        if (!currentUser) {
            // not logged in so redirect to login page with the return url
            return next({ path: '/login', query: { returnUrl: to.path } });
        }

        // check if route is restricted by role
        if (authorize.length && !authorize.includes(currentUser.role)) {
            // role not authorised so redirect to home page
            return next({ path: '/' });
        }
    }

    next();
})
 

Vue.js Tutorial Services Folder

Path: /src/_services

The _services layer handles all http communication with backend apis for the application, each service encapsulates the api calls for a content type (e.g. users) and exposes methods for performing various operations (e.g. CRUD operations). Services can also have methods that don't wrap http calls, for example the authenticationService.logout() method just removes the currentUser object from localStorage and sets it to null in the application.

I like wrapping http calls and implementation details in a services layer because it provides a clean separation of concerns and simplifies the vue components that use the services.

 

Vue.js Tutorial Authentication Service

Path: /src/_services/authentication.service.js

The authentication service is used to login and logout of the application, to login it posts the user's credentials to the /users/authenticate route on the api, if authentication is successful the user details including the token are added to local storage, and the current user is set in the application by calling currentUserSubject.next(user);.

The logged in user details are stored in local storage so the user will stay logged in if they refresh the browser and also between browser sessions until they explicitly logout. If you don't want the user to stay logged in between refreshes or sessions the behaviour could easily be changed by storing user details somewhere less persistent such as session storage which would persist between refreshes but not browser sessions, or you could remove the calls to localStorage which would cause the user to be logged out if the browser is refreshed.

There are two properties exposed by the authentication service for accessing the currently logged in user. The currentUser observable can be used when you want a component to reactively update when a user logs in or out, for example in the App.vue component so it can show/hide the main nav bar when the user logs in/out. The currentUserValue property can be used when you just want to get the current value of the logged in user but don't need to reactively update when it changes, for example in the router.beforeEach() hook inside router.js which restricts access to routes by checking if the user is currently logged in and authorised.

import { BehaviorSubject } from 'rxjs';

import config from 'config';
import { requestOptions, handleResponse } from '@/_helpers';

const currentUserSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('currentUser')));

export const authenticationService = {
    login,
    logout,
    currentUser: currentUserSubject.asObservable(),
    get currentUserValue () { return currentUserSubject.value }
};

function login(username, password) {
    return fetch(`${config.apiUrl}/users/authenticate`, requestOptions.post({ username, password }))
        .then(handleResponse)
        .then(user => {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
            currentUserSubject.next(user);

            return user;
        });
}

function logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    currentUserSubject.next(null);
}
 

Vue.js Tutorial User Service

Path: /src/_services/user.service.js

The user service contains just a couple of methods for retrieving user data from the api, it acts as the interface between the Vue application and the backend api.

I included the user service to demonstrate accessing secure api endpoints with the http authorization header set after logging in to the application, the auth header is set with a JWT token in headers() function of the request-options.js helper above. The secure endpoints in the example are fake/mock routes implemented in the fake-backend.js helper above.

import config from 'config';
import { handleResponse, requestOptions } from '@/_helpers';

export const userService = {
    getAll,
    getById
};

function getAll() {
    return fetch(`${config.apiUrl}/users`, requestOptions.get())
        .then(handleResponse);
}

function getById(id) {
    return fetch(`${config.apiUrl}/users/${id}`, requestOptions.get())
        .then(handleResponse);
}
 

Vue.js Tutorial App Folder

Path: /src/App

The app folder is for vue components and other code that is used only by the app component in the tutorial application.

 

Vue.js Tutorial App Component

Path: /src/app/App.vue

The app component is the root component for the vue tutorial application, it contains the outer html, router-view and main nav bar for the example app.

It subscribes to the currentUser observable in the authentication service so it can reactively show/hide the main navigation bar when the user logs in/out of the application. I didn't worry about unsubscribing from the observable here because it's the root component of the application, so the only time the component will be destroyed is when the application is closed which would destroy any subscriptions as well.

The app component contains a logout() method which is called from the logout link in the main nav bar to log the user out and redirect them to the login page.

<template>
    <div>
        <nav v-if="currentUser" class="navbar navbar-expand navbar-dark bg-dark">
            <div class="navbar-nav">
                <router-link to="/" class="nav-item nav-link">Home</router-link>
                <router-link v-if="isAdmin" to="/admin" class="nav-item nav-link">Admin</router-link>
                <a @click="logout" class="nav-item nav-link">Logout</a>
            </div>
        </nav>
        <div class="jumbotron">
            <div class="container">
                <div class="row">
                    <div class="col-sm-6 offset-sm-3">
                        <router-view></router-view>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { authenticationService } from '@/_services';
import { router, Role } from '@/_helpers';

export default {
    name: 'app',
    data () {
        return {
            currentUser: null
        };
    },
    computed: {
        isAdmin () {
            return this.currentUser && this.currentUser.role === Role.Admin;
        }
    },
    created () {
        authenticationService.currentUser.subscribe(x => this.currentUser = x);
    },
    methods: {
        logout () {
            authenticationService.logout();
            router.push('/login');
        }
    }
};
</script>
 

Vue.js Tutorial Admin Folder

Path: /src/admin

The admin folder is for vue components and other code that is used only by the admin page component in the tutorial application.

 

Vue.js Tutorial Admin Page Component

Path: /src/admin/AdminPage.vue

The admin page calls the user service to get all users from a secure api endpoint and displays them in a html list. The page is restricted to users in the 'Admin' role.

<template>
    <div>
        <h1>Admin</h1>
        <p>This page can only be accessed by administrators.</p>
        <div>
            All users from secure (admin only) api end point:
            <ul v-if="users.length">
                <li v-for="user in users" :key="user.id">
                    {{user.firstName + ' ' + user.lastName}}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import { authenticationService, userService } from '@/_services';

export default {
    data () {
        return {
            user: authenticationService.currentUserValue,
            users: []
        };
    },
    created () {
        userService.getAll().then(users => this.users = users);
    }
};
</script>
 

Vue.js Tutorial Home Folder

Path: /src/home

The home folder is for vue components and other code that is used only by the home page component in the tutorial application.

 

Vue.js Tutorial Home Page Component

Path: /src/home/HomePage.vue

The home page component is displayed after signing in to the application, it contains a simple welcome message and the current user record. The component gets the current user from the authentication service and then fetches the current user from the api by calling the userService.getById(currentUser.id) method from the created() vue lifecycle hook.

We only really needed to get the user from the authentication service, but I included getting it from the user service as well to demonstrate fetching data from a secure api endpoint.

<template>
    <div>
        <h1>Home</h1>
        <p>You're logged in with Vue.js & JWT!!</p>
        <p>Your role is: <strong>{{currentUser.role}}</strong>.</p>
        <p>This page can be accessed by all authenticated users.</p>
        <div>
            Current user from secure api end point:
            <ul v-if="userFromApi">
                <li>{{userFromApi.firstName}} {{userFromApi.lastName}}</li>
            </ul>
        </div>
    </div>
</template>

<script>
import { userService, authenticationService } from '@/_services';

export default {
    data () {
        return {
            currentUser: authenticationService.currentUserValue,
            userFromApi: null
        };
    },
    created () {
        userService.getById(this.currentUser.id).then(user => this.userFromApi = user);
    }
};
</script>
 

Vue.js Tutorial Login Folder

Path: /src/login

The login folder is for vue components and other code that is used only by the login page component in the tutorial application.

 

Vue.js Tutorial Login Page Component

Path: /src/login/LoginPage.vue

The login page component contains a login form with username and password fields. It displays validation messages for invalid fields when the user attempts to submit the form or when a field is touched. If the form is valid the component calls the authenticationService.login(username, password) method, if login is successful the user is redirected back to the original page they were trying to access.

There's an info alert message above the form with the login details for two example users, a normal user in the User role and an admin user in the Admin role.

Form validation is handled with the Vuelidate library, for more info about validating forms with Vuelidate check out Vue.js + Vuelidate - Form Validation Example.

<template>
    <div>
        <div class="alert alert-info">
            <strong>Normal User</strong> - U: user P: user<br />
            <strong>Administrator</strong> - U: admin P: admin
        </div>
        <h2>Login</h2>
        <form @submit.prevent="onSubmit">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" v-model.trim="$v.username.$model" name="username" class="form-control" :class="{ 'is-invalid': submitted && $v.username.$error }" />
                <div v-if="submitted && !$v.username.required" class="invalid-feedback">Username is required</div>
            </div>
            <div class="form-group">
                <label htmlFor="password">Password</label>
                <input type="password" v-model.trim="$v.password.$model" name="password" class="form-control" :class="{ 'is-invalid': submitted && $v.password.$error }" />
                <div v-if="submitted && !$v.password.required" class="invalid-feedback">Password is required</div>
            </div>
            <div class="form-group">
                <button class="btn btn-primary" :disabled="loading">
                    <span class="spinner-border spinner-border-sm" v-show="loading"></span>
                    <span>Login</span>
                </button>
            </div>
            <div v-if="error" class="alert alert-danger">{{error}}</div>
        </form>
    </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators';

import { router } from '@/_helpers';
import { authenticationService } from '@/_services';

export default {
    data () {
        return {
            username: '',
            password: '',
            submitted: false,
            loading: false,
            returnUrl: '',
            error: ''
        };
    },
    validations: {
      username: { required },
      password: { required }
    },
    created () {
        // redirect to home if already logged in
        if (authenticationService.currentUserValue) { 
            return router.push('/');
        }

        // get return url from route parameters or default to '/'
        this.returnUrl = this.$route.query.returnUrl || '/';
    },
    methods: {
        onSubmit () {
            this.submitted = true;

            // stop here if form is invalid
            this.$v.$touch();
            if (this.$v.$invalid) {
                return;
            }

            this.loading = true;
            authenticationService.login(this.username, this.password)
                .then(
                    user => router.push(this.returnUrl),
                    error => {
                        this.error = error;
                        this.loading = false;
                    }
                );
        }
    }
};
</script>
 

Vue.js Tutorial Index HTML File

Path: /src/index.html

The base index html file contains the outer html for the whole tutorial application. When the app is started with npm start, Webpack bundles up all of the vue code into a single javascript file and injects it into the body of the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js - Role Based Authorization Tutorial & Example</title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/4.2.0/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        a { cursor: pointer; }
    </style>
</head>
<body>
    <div id="app"></div>
</body>
</html>
 

Vue.js Tutorial Main Entry File

Path: /src/index.js

The root index.js file bootstraps the vue tutorial application by rendering the App component into the #app div element defined in the base index html file above.

The boilerplate application uses a fake / mock backend by default, to switch to a real backend api simply remove the fake backend code below the comment // setup fake backend.

import Vue from 'vue';
import Vuelidate from 'vuelidate';

import { router } from './_helpers';
import App from './app/App';

// setup fake backend
import { configureFakeBackend } from './_helpers';
configureFakeBackend();

Vue.use(Vuelidate);

new Vue({
    el: '#app',
    router,
    render: h => h(App)
});
 

Vue.js Tutorial Babel RC (Run Commands)

Path: /.babelrc

The babel config file defines the presets used by babel to transpile the Vue and ES6 code. The babel transpiler is run by webpack via the babel-loader module configured in the webpack.config.js file below.

{
    "presets": [
        "env",
        "stage-0"
    ]
}
 

Vue.js Tutorial Package.json

Path: /package.json

The package.json file contains project configuration information including package dependencies which get installed when you run npm install. Full documentation is available on the npm docs website.

{
    "name": "vue-role-based-authorization-example",
    "version": "1.0.0",
    "repository": {
        "type": "git",
        "url": "https://github.com/cornflourblue/vue-role-based-authorization-example.git"
    },
    "license": "MIT",
    "scripts": {
        "start": "webpack-dev-server --open"
    },
    "dependencies": {
        "rxjs": "^6.4.0",
        "vue": "^2.6.8",
        "vue-router": "^3.0.2",
        "vuelidate": "^0.7.4"
    },
    "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.5",
        "babel-preset-env": "^1.6.1",
        "babel-preset-stage-0": "^6.24.1",
        "babel-preset-vue": "^2.0.2",
        "css-loader": "^2.1.1",
        "html-webpack-plugin": "^3.2.0",
        "path": "^0.12.7",
        "vue-loader": "^15.7.0",
        "vue-template-compiler": "^2.6.8",
        "webpack": "^4.29.6",
        "webpack-cli": "^3.2.3",
        "webpack-dev-server": "^3.2.1"
    }
}
 

Vue.js Tutorial Webpack Config

Path: /webpack.config.js

Webpack is used to compile and bundle all the project files so they're ready to be loaded into a browser, it does this with the help of loaders and plugins that are configured in the webpack.config.js file. For more info about webpack check out the webpack docs.

The webpack config file also defines a global config object for the application using the externals property, you can also use this to define different config variables for your development and production environments.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    mode: 'development',
    resolve: {
        extensions: ['.js', '.vue']
    },
    module: {
        rules: [
            {
                test: /\.vue?$/,
                loader: 'vue-loader'
            },
            {
                test: /\.js?$/,
                loader: 'babel-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.vue'],
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        }
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({ template: './src/index.html' })
    ],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            apiUrl: 'http://localhost:4000'
        })
    }
}

 


Need Some Vue Help?

Search fiverr for freelance Vue developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by