Sending Session Cookies with Axios

  • 16 May 2019
Post image

Set cookies with Axios from a browser

If you want to use axios to send the browser’s SessionCookie and other information directly to the server, set it as follows.

axios.get('url',
  {
    withCredentials: true
  }
)

And the server side allows the following. (Use cors) This time, the example is for the case where the server side is NoneJS express, but it is the same for other languages and frameworks.

import * as express from "express";
const cors = require('cors')
const app = express()
app.use(cors({credentials: true, origin: true}));

This is the only way for Axios to communicate with the server using the browser’s session information. Note that you need to set credentials on the server side as well. By the way, HTTPOnly cookies are also sent in this way, so it is better to set HTTPOnly for security reasons. Please think carefully about the security of other API communication.(Check out this article

Set cookies with Axios from the server side

There are times when you want to hit the WebAPI from the server side before responding to the browser.
And of course, there are times when you want to send a browser cookie to that communication as well. In this case, withCredentials cannot send browser cookies to the endpoint. (Naturally, since the communication is from the server side.)
In such a case, you can set the cookie as follows

// In Server-side 
auth.get('/', function(req, res, next) {
      axios.get('url',
        headers: {
            Cookie: req.headers.cookie
        }
      )
});

Just set the cookie in the Express request in the headers. Now, the cookie information shared to the server side can be shared to other backends. For example, assume that you have multiple backends, such as in a microservice design.
The security of HTTP communication is very important, so please refer to the following

Countermeasures for access to non-authenticated APIs
Countermeasures for access to non-authenticated APIs
Menu As I wrote in my previous article, static sites are more …
> Read More

(Article migrated from another blog)

You May Also Like