auth0-blog / vue-jwt-authentication

MIT License
509 stars 112 forks source link

Set header after login? #8

Open cannap opened 8 years ago

cannap commented 8 years ago

I have a question what is the best way to set the Header in auth.login() {}?

current solution:

import Vue from 'vue'; ....

   login(context, creds, redirect) {
        context.$http.post(LOGIN_URL, creds).then((data) => {

            localStorage.setItem('id_token', data.data.id_token)
            Vue.http.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('id_token');

            this.user.authenticated = true
            if (redirect) {
                router.go(redirect)
            }
        }).catch(({data}) => {
            context.error = data
        })

    },

i solve in a other way i switch to VUEX thank for the tutorial

chenkie commented 8 years ago

I'm a bit unclear on what you'd like to achieve. Are you wanting to send a header on the POST request that you have in your login method? Or are you wanting to set up a global Authorization header with the user's JWT if login is successful?

cannap commented 8 years ago

Hi i solved with interceptors

Vue.http.interceptors.push((request, next) => {
    const token = getLoginToken();
    if (token) {
        request.headers['Authorization'] = 'Bearer ' + token
    }

    next((response) => {
        if (response.status === 401 && response.request.url !== "/session/create") {
            //Todo: no hardcoded routes
            window.location.pathname = "/admin/login"
        }
    });
});

The Tutorials show:

//index.js
Vue.http.headers.common['Authorization'] = auth.getAuthHeader();

but this will first work after a refresh