How to logout once jwt token is expired

14,579

Refer to the axios documentataion: https://github.com/axios/axios

import axios from 'axios';

export default () => {
    let headers = {
        'cache-control': 'no-cache'
    };
    let accessToken = localStorage.getItem('jwt-token');

    if (accessToken && accessToken !== '') {
        headers.Authorization = accessToken;

    };
    const instance = axios.create({
        baseURL: 'http://localhost:8086/',
        headers: headers
    });

    instance.interceptors.response.use((response) => {
        if(response.status === 401) {
             //add your code
             alert("You are not authorized");
        }
        return response;
    }, (error) => {
        if (error.response && error.response.data) {
             //add your code
             return Promise.reject(error.response.data);
        }
        return Promise.reject(error.message);
    });

    return instance;
}
Share:
14,579
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am working on a web-app using node.js and vue.js, I am doing authentication and maintaining session using jwt and passport.js using passport-jwtstrategy

    I have done all the things from creating jwt to protecting routes all the things now my issue is while generating jwt I am passing expiresIn:3600 so I want to auto-logout my user from Ui and remove token from localStorage once it has been one hour

    On decoding my jwt I am getting

     {
      "name": "Dheeraj",
      "iat": 1571896207,
      "exp": 1571899807
    }
    

    So how can I get the real-time when to logout

    In my auth.js vue store file my logout code when user clicks on logout is

    logout({ commit }) {
            return new Promise((resolve, reject) => {
                localStorage.removeItem('jwt-token')
                localStorage.removeItem('user-name')
                commit('setAuthUser', null)
                resolve(true)
            })
    
        },
    

    In the same file, I have a method getAuthUser which is running whenever a page is loading or reloading to check to protect rout and guestUser

    getAuthUser({ commit, getters }) {
            const authUser = getters['authUser']
            const token = localStorage.getItem('jwt-token')
            const isTokenValid = checkTokenValidity(token)
            if (authUser && isTokenValid) {
                return Promise.resolve(authUser)
            }
    
            commit('setAuthUser', token)
            commit('setAuthState', true)
            debugger
            return token
    
    
        }
    

    So how can I logout once my token is expired Anyone out here please guide me how can I logout once the token is expired

    Edit

    In my router.js file

    router.beforeEach((to, from, next) => {
    store.dispatch('auth/getAuthUser')
        .then((authUser) => {
            const isAuthenticated = store.getters['auth/isAuthenticated']
    
            if (to.meta.onlyAuthUser) {
                if (isAuthenticated) {
                    next()
                } else {
                    next({ name: 'login' })
                }
            } else if (to.meta.onlyGuestUser) {
                if (isAuthenticated) {
                    next({ name: 'welcome' })
                } else {
                    next()
                }
            } else {
                next()
            }
        })
    

    })

    from my auth file I am calling get authUser which I have already mention above

    for checking token validity I am using this code

    function checkTokenValidity(token) {
    if (token) {
        const decodedToken = jwt.decode(token)
        return decodedToken && (decodedToken.exp * 1000) > new Date().getTime()
    
    }
    return false
    

    }

    but it returns false when I am on login page and there is no token there but once I am loged in it shows null

    My global api file

        import axios from 'axios';
    
    export default () => {
        let headers = {
            'cache-control': 'no-cache'
        };
        let accessToken = localStorage.getItem('jwt-token');
    
        if (accessToken && accessToken !== '') {
            headers.Authorization = accessToken;
    
        };
        return axios.create({
            baseURL: 'http://localhost:8086/',
            headers: headers
        });
    }
    
  • Admin
    Admin over 4 years
    hey it doesn't help I have given expiry time of 20 sec so when I am refreshing after that it is not going in any condition not here if(response.status === 401) { neither here (error) => {
  • Max Peng
    Max Peng over 4 years
    After you refresh the page, you may need to seed a request to the backend to verify the token. Otherwise, the interceptor will not take effect.
  • Admin
    Admin over 4 years
    yup there are api's which are running on page refers and at backend I am checking them with passport also
  • farahm
    farahm over 3 years
    Ok, this is for reacting when token has expired and user is doing post/get via axios using expired token. How to deal with page refresh, or when user just enters a url directly into browser?
  • Max Peng
    Max Peng over 3 years
    Refresh the page and enter URL directly basically are the same, the browser will load the HTML, CSS, Javascript first then send the AJAX request to the server.