Saturday 29 June 2019

NuxtJS $axios Send Cookies With Request

I am using NuxtJS's $axios module and I am interacting with a backend API that set's an authentication cookie for further authenticated requests after logging in. I've looked into withCredentials: true, but it is still not cooperating properly.

Do I need to set a specific header value or is something wrong with my axios configuration?

I just want to keep and use this cookie received from logging in successfully and use it in the next requests to make authenticated requests.

// nuxt.config.js
axios : {
    ...
    credentials: true,
    withCredentials : true,
    requestInterceptor: (config, {store}) => {
        config.headers.common['Content-Type'] = 'application/json';
        config.headers.common['API-Key'] = 'my_api_key';
        return config
    },
    ...
},

and here is where I am making my axios request


async asyncData({ $axios}) {
    try {
        // this response sends back an authentication cookie
        const login_response = await $axios.$post("my_login_route",{
            password : this.password,
            username : this.email,
        });

        if(login_response.success){
            // how i send my cookie to this route to prove im authenticated?
            const authenticated = await $axios.$get("my_url");
            console.log(authenticated); // always false; doesn't send cookie recieved in login $post request
        }else{
            console.log("Invalid username or password");
        }
    } catch(error) {
        console.log(error);
    }
}

I've made a test page with making a simple request to check if the user is authenticated. Turns out, the axios settings in the nuxt.config.js are NOT being applied here.

I need the axios configuration to apply to not just the base URL, but to my API routes. Here is a test method that activates when I press a test button:

check_auth : async function(){
    try {
        const response = await this.$axios.$get("https://<my_url>/Utility/IsAuthenticated/");
        console.log("IS AUTH:");
        console.log(response.isAuthenticated);
    }catch(error){
        console.log("something went wrong.");
    }
},

HTTP REQUEST HEADERS FOR AXIOS REQUEST MADE RIGHT ABOVE As you can see, there are no cookies or API-Key headers that I specified in the axios config.

Host: <my_url>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:67.0) Gecko/20100101 Firefox/67.0
Accept: application/json, text/plain
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:1337/send/account
Origin: http://localhost:1337
DNT: 1
Connection: keep-alive

What do I need to change in my axios nuxt.config.js section to allow the axios configuration to apply to my api route? Do i need to use the proxy:{} section?

Please help!!



from NuxtJS $axios Send Cookies With Request

No comments:

Post a Comment