Thursday 25 June 2020

Better understanding of Axios handling of httpOnly cookies

I've developed a Flask backend and am experimenting with a JavaScript frontend. I am much less familiar with JS than backend issues. I was able to spin up a simple CRUD API in Flask. After learning about Bearer JWT in LocalStorage vs httpOnly Cookies, I figured that httpOnly Cookies were a good way to go.After about a month of banging my head against the wall and looking at forums, I finally broke through, but I don't fully understand why this works. Can someone help me out? I've got questions.So first off { withCredentials: true} is not magic. There are lot of posts that suggest it-just-handles-it™. However, while I was able to log in and see in my console.log the cookie was set correctly, I could not figure out how to pass the token to the backend on the next GET request. Perhaps this is just for Authorization headers only or Basic Auth? Do I still need to include it?Is parsing the cookie standard? Should the token be persisted in LocalStorage? This seems to defeat the purpose of an httpOnly cookie, right?It's become clear that sending the credentials to my Flask backend require modifying the axios interceptors to send a custom header. axios-token-interceptor seems like a good library to help with this. Are there other libraries or recommended ways to do this?Anything else I should be thinking about?const http = require('http'); const axios = require('axios'); const tokenProvider = require('axios-token-interceptor'); var cookie = require('cookie'); const hostname = '127.0.0.1'; const port = 80; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); const instance = axios.create({ withCredentials: true, baseURL: 'MY-URL', mode: 'cors', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }) instance.post('/auth/login', { 'username': 'USERNAME', 'password': 'PASSWORD' } ) .then((response) => { console.log(response.data); const cookies = cookie.parse(response.headers['set-cookie'][0]); console.log(cookies); // console.log(response.status); // console.log(response.statusCode); // console.log(response.statusText); // console.log(response.headers); // console.log(response.config); setTimeout(function(){ instance.interceptors.request.use(tokenProvider({ token: cookies.access_token_cookie, header: 'Cookie', headerFormatter: (token) => 'access_token_cookie=' + token, })); instance.get('ENDPOINT', { withCredentials: true},) .then((response) => { console.log(response.data); }); }, 4000); }) server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });

Submitted June 25, 2020 at 03:19PM by chasetheskyforever

No comments:

Post a Comment