PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to manage and send httpOnly stored jwt cookies within React and Axios

 October 13, 2022     axios, cookie-httponly, cookies, express, reactjs     No comments   

Issue

I'm actively trying to gain knowledge on httpOnly cookie and found out lots of article on it that why should we use it.

But I haven't seen any practical example of how to work with it. From few trial and error, I came to knew that we can't set httpOnly flag in browser and needed to be done on server. So I, used cookie-parser library accordingly:

const express = require('express');
var cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

app.post('/generateToken', (req, res) => {
    res.cookie('AccessToken', JWT_AUTH_TOKEN, {
        expires: new Date(new Date().getTime() + 30 * 1000),
        sameSite: 'strict',
        httpOnly: true,
        
    })
    res.cookie('RefreshToken', JWT_REFRESH_TOKEN, {
        expires: new Date(new Date().getTime() + 31557600000),
        sameSite: 'strict',
        httpOnly: true,
    }).send("hello")
    
});

app.listen(process.env.PORT || 5050);

By this I successfully get the cookie stored in my browser with all the property like sameSite, HttpOnly except secure:true as I'm on local host. But the problem is as we cant access these httpOnly token with javascript, How do I send it to particular routes with proper header like below

let token = req.headers['authorization'];

and send httpOnly cookie refreshToken to lets say /refresh Route to get new accessTokens with Axios or whats the way of doing it?


Solution

When you have set the cookies with HttpOnly flag, the cookies will be automatically sent via HTTP request from the browser to the server. You don't have to explicitly set it in HTTP Header.

With cors installed at the server, you can access the cookie with req.cookies.

I am not sure with axios, but if using fetch API, we will need to add credential:'include' option in the fetch API, so that the HttpOnly cookies can be set.

Take a look at this post.



Answered By - Sem
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing