HttpOnly and Secure Flag

Introduction

HttpOnly is a flag added to cookies that tell the browser not to display the cookie through client-side scripts (document.cookie and others). The agenda behind HttpOnly is not to spill out cookies when an XSS flaw exists, as a hacker might be able to run their script but the fundamental benefit of having an XSS vulnerability is lost.

Secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of a the cookie in clear text.

How to test

we can use the browser extension for view the cookies and flags are set or not.

For Chrome

Use EditThisCookie extension to view the cookies.

For Firefox

Use Cookie Editor extension to view the cookies.

Steps

  1. Install the extension in your browser.

  2. Go to the site and open the cookie extension.

  3. You can see the each cookie and the flag is set or not

Solutions

PHP

Method 1

We can access to the php.ini file, add below code in end of the file to make the HttpOnly and Secure flag.

session.cookie_httponly=On
session.cookie_secure=On

Method 2

We can add the ini_set function in top of the each php page.

ini_set('session.cookie_httponly',1);
ini_set('session.use_only_cookies',1);
ini_set('session.cookie_secure', 1);

Method 3

We can also use header function to mark the cookie as HttpOnly and Secure flag. We have to add in top of the each php page.

header("Set-Cookie: key=value; path=/; domain=www.tutorialshore.com; HttpOnly; Secure; SameSite=Strict");

ASP.NET

We have to access the web.config file and add the below code to make the HttpOnly and Secure flag.

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" />
</system.web>

NODE.JS

We have to insert the below code in the program.

res.cookie('sessionid', '1', { httpOnly: true });

References

Last updated

Was this helpful?