Pages

Monday, December 20, 2021

JWT token in CORS session Cookie

This article is based on the experience of Nextjs frontend (a framework of react) and Nodejs backend with Express and cors middleware.

 

Without these settings in both front end and backend - session cookie will not be accepted (both by server and browser).


N.B. This is workable only in localhost or over HTTPS only. HTTP and trivial IP address other than localhost will not work.

 

 In front end, we need to set these 2 header options along with Ajax request ( native fetch or with axios ):


  credentials: 'include' 

and  

  mode: 'cors'  

 

 

In back end, we need to use cors library or middleware along with the parameter/option

  origin: <exact client url> 

and 

  credentials: true

 

The cookie setting header should include these options:

  sameSite: 'none',
  secure:      true,
  maxAge:    Cookie expiry time in milliseconds
  httpOnly:   true

 

 

We should use CSRF cooke library for further protection from CSRF attack.


Alternatively we can use Authorization header that bears the token manually saved in local storage (or browser cookie), and should take necessary protection from XSS attack.