Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle login API token in Vue JS

I am using following Login component:

var Login = Vue.extend({
    template: '#auth',
    data: function () {
        return {username: '',password: '',errorMessage:''};
    },
    methods : {
        login: function (e) {
            var _this = this;
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:_this.username,
                    password: _this.password
                },
                success: function (data) {
                // store the token in global variable ??
                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        }
    }
});

The login API returns a token string for successful authentication. Should I store it in global variable or local storage ? Is there any filter that I can use to check if the user is logged in to application and then redirect accordingly?

like image 970
Vivek Sadh Avatar asked Apr 24 '17 07:04

Vivek Sadh


People also ask

How do you use Vue tokens?

Store Token in vuex In our store, we add the user and token data in our state and set them to null initially. You can use the token to see if the user is logged in or not. If the token is null , then we are not logged in, but if it's set to something, then we are probably logged in.


1 Answers

The best way is by using VUEX : a vue state management system

In you vuex store.js file you can define the user's state as follows:

const store = new Vuex.Store({ 
    state: { 
        user: {
            userName:'',
            loggedInStatus: true,
            authToken: ''
        }
    }, 
    mutations: { 
        addWebToken: function(state, webToken){
            state.user.authToken = webToken;
        },
        removeWebToken: function(state){
            state.user.authToken = '';
        }
    },
    actions: {
        login: function(context, userInput){
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:userInput.username,
                    password: userInput.password
                },
                success: function (data) {
                // store the token in global variable ??

                context.commit('addWebToken', webToken); // pass the webtoken as payload to the mutation

                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        },
        logput: function(context){
            //your logout functionality
            context.commit('removeWebToken');
        }
    }

})

now in your component > methods > login() you can dispatch the login action you have declared in your vuex srore as follows

var Login = Vue.extend({
        template: '#auth',
        data: function () {
            return {username: '',password: '',errorMessage:''};
        },
        methods : {
            login: function () {
                //passing the username and password in an object as payload to the login action
                this.$store.dispatch('login', {username: this.username, ppassword: password});
            },
            logout: function(){
                this.$store.dispatch('logout');
            }
        }
    });

the advantagess of doing so :

  • you have a centralized state where you can manage the user info in the state

  • you can save the state in local store or as cookies using vuex- persisted state as shown below, which would save the state of your user including the webtoken and even the state is persisted on page refreshes also. This means that when user is logged in and refreshes the page , since te user state from the store is kept you can access the webtoken and keep the user logged in.

const store = new Store({ // ... plugins: [ createPersistedState({ getState: (key) => Cookies.getJSON(key), setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true }) }) ] })

You can add the vuex persisted state plugin to your store and use jscookies library to save the state of your user in cookies or else local store if you want by following the vuex-persistedstate documentation

like image 178
Vamsi Krishna Avatar answered Oct 08 '22 20:10

Vamsi Krishna