Basic Authentication using auth.nuxt.js

Dinushanka
ITNEXT
Published in
6 min readMay 9, 2018

--

Souce

Introduction

Recently, I got to know an easy way to get through the authentication using the “auth-module” provided by nuxt js. You can have a look at the module at https://auth.nuxtjs.org .They’ve provided with some examples but this is how I implemented.

To get started, you have to install few modules including the vue-cli module.

npm install -g vue-cli

After installing the vue-cli you can start off with the boilerplate code provided by nuxtjs. Just input the below command and change the name of the project.

vue init nuxt-community/starter-template <project-name>

CD into the project directory and then do a npm install or yarn install. To start off the project you can do a npm run dev. All the commands that can be used is clearly given in the package.json file under “scripts”

{
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
"precommit": "npm run lint"
}
}

Now our base project setup is completed.

Getting Started with auth.nuxtjs

To get started, you’ll need to install the following packages.

npm install --save @nuxtjs/auth @nuxtjs/axios @nuxtjs/toast bootstrap-vue

I have selected boostrap-vue ( ) for this tutorial. If you need you can use vuetify or any other UI framework. Remember to use the @nuxtjs based version of axios.

OK. Now we have to configure each package to work with nuxt js. So let’s get started with auth. Goto nuxt.config.js at the root of the project.

  1. Add the relevant modules
modules: [
'@nuxtjs/axios',
'@nuxtjs/auth',
'@nuxtjs/toast',
'bootstrap-vue/nuxt'
],

2. Add the toast message Configurations

toast: {
position: 'top-right',
duration: 2000
}

3. Add the axios baseURL. This will be your APIs base url

axios: {
baseURL: ‘http://192.168.8.141:5000/api/v1'
},

4. Let’s setup the loading

loading: {
name: 'chasing-dots',
color: '#ff5638',
background: 'white',
height: '4px'
},

5. Finally add the most important auth module configurations

auth: {
strategies: {
local: {
endpoints: {
login: {url: '/user/login', method: 'post', propertyName: 'token' },
logout: false,
user: {url: '/user/user', method: 'get', propertyName: 'data'},
},
tokenRequired: true,
tokenType: 'Bearer'
},
facebook: {
client_id: 'your facebook app id',
userinfo_endpoint: 'https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email',
scope: ['public_profile', 'email']
},
google: {
client_id: 'your gcloud oauth app client id'
},
},
redirect: {
login: '/?login=1',
logout: '/',
user: '/profile',
callback:'/'
}

OK, Let’s go through the above configuration one by one. [ local, facebook, google, twitter, github oAuth ] are the authentication strategies included with the auth.nuxtjs module. Other than that you also can add custom stategies to the configuration. Refer the auth.nuxtjs configuration for that.

If you take a look at the local strategy, there is a field called endpoints. The login endpoint refers to your API’s authentication route. Method parameter is a POST and the propertyName means where the access token is present in the response. For your reference, this is how the propertyName is set inside the auth.nuxtjs module.

// Taken from the nuxt-authreturn this.ctx.app.$axios
.request(_endpoint)
.then(response => {
if (_endpoint.propertyName) {
return getProp(response.data, _endpoint.propertyName)
} else {
return response.data
}
})

I got into a problem here. The auth token came as a header parameter and I couldn’t figure out a way to resolve this issue. So I changed the API. If you find a way to get through this issue, please mention in the comments.

Then you can use the logout field to define the logout url of your API. Since REST is stateless we wont need this. The user parameter helps to retrive the user information when logged in. You also can define the tokenType “Bearer”, then it will be prepend to the auth token.

Then let’s go through the facebook auth strategy. Here you only have to define the scope, clientId and the loginurl. I’ve used the facebook API version 2.12 but it will be deprecated soon. Same goes with google, twitter and github.

Then you have to specify the redirect urls. So in there, you can speficy the logout page url, user profile url and the callback url which will be used in social logins. So If you are having your own authflow, callback url will help you to exchange a social login token with an API generated token. Nuxt can listen to the url params using the following code.

watch: {
$route() {
//do something with the url params set
}
},

I’ll include the soucecode in my github at the end, So that you’ll see what I have done with the url params. Oh! and one last thing, don’t forget to create the index.js file under /store director to activate the Vuex store.

Sample UI

What we are making

Let’s build up a sample ui to test out the configuration. Delete all the default code in index.vue inside pages and now your index.vue should look like this.

<template>
<section class="container">
<div></div>
</section>
</template>

Then lets create a beautiful form. Just copy and paste the given below code.

<template>
<section class="container">
<div>
<b-form>
<b-form-group description="Let us know your Email." label="Enter your Email" label-for="username">
<b-form-input id="username" v-model="email" type="email" required></b-form-input>
</b-form-group>
<b-form-group description="Let us know your Password." label="Enter your Password" label-for="pw">
<b-form-input id="pw" v-model="password" type="password"> </b-form-input>
</b-form-group>
<b-button-group size="sm">
<b-button @click="facebook" variant="outline-success">Facebook</b-button>
<b-button @click="login" variant="outline-success">Login</b-button>
<b-button @click="google" variant="outline-success">Google</b-button>
<b-button @click="logout" variant="outline-success">Logout</b-button>
<b-button @click="check" variant="outline-success">Check</b-button>
<b-button to="/callback" variant="outline-success">Callback</b-button>
</b-button-group>
</b-form>
</div>
</section>
</template>
<script>export default {
data() {
return {
email:'',
password:''
}
},
mounted() {},
watch: {},
components: {},
methods: {
google(){},
facebook(){},
login(){},
logout(){},
check(){},
}
}
</script><style>.container {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
</style>

Given below are the method definitions

google()- Google Login
facebook()- Facebook Login
login()- Local Authentication
logout() — Logout function
check() — Check whether the user is logged in or now. Check the console for the output

Note that I’ve used bootstrap-vue to build the form. Now we are at the final step. Let’s create the methods required to login.

async google(){
await this.$auth.loginWith('google').catch(e => {
this.$toast.show('Error', {icon: "fingerprint"});
})
},
async facebook(){
await this.$auth.loginWith('facebook').catch(e => {
this.$toast.show('Error', {icon: "fingerprint"});
})
},
async login() {
try {
this.$toast.show('Logging in...', {icon: "fingerprint"});
await this.$auth.loginWith('local', {
data: {
"email": this.email,
"password": this.password
}
}).catch(e => {
this.$toast.error('Failed Logging In', {icon: "error_outline"});
});
if (this.$auth.loggedIn) {
this.$toast.success('Successfully Logged In', {icon: "done"});
}
} catch (e) {
this.$toast.error('Username or Password wrong', {icon: "error"});
}
},
check(){
console.log(this.$auth.loggedIn)
},
logout() {
this.$toast.show('Logging out...', {icon: "fingerprint"});
this.$auth.logout()
},

I have used Google Material Icons as toast icons. You just have to put the material icons cdn under the links of the header field. Now we are almost done. To check wheter you have logged in or not, use the console. Check for the cookies, localStorage. Setting up all these things are done automatically by the nuxt-auth module itself.

Vuex store after logging in with Gmail
Cookies
localStorage after logging with Gmail

Create a page called callback.vue inside the pages and add the following code.

<template>
<div>
<h1>You are Secure</h1>
<b-button to="/" variant="success">Callback</b-button>
</div>
</template>
<script>
export default {
middleware: ['auth']
}
</script><style scoped></style>

Note that I have added a new middleware called [‘auth’]. Nuxt-auth module will automatically create a middleware for you, so that you don’t have to write your own middleware to check whether you are authenticated before redirecting to the page. This is the end of this tutorial. I’ll be doing more nuxt tutorials as I get time. Stay in touch ❤ . Special thanks goes to Rooshan Akthar for introducing me to auth.nuxt.js

--

--