How to set the secure flag on cookies

0 votes
In my web application, I want to set the Secure flag to ensure that cookies are only transmitted over HTTPS. How do I configure cookies with the Secure flag, and are there other flags that improve cookie security, such as HttpOnly and SameSite?

Clear steps to set secure cookies, particularly in Node.js or other server environments, would be appreciated.
Nov 13, 2024 in Cyber Security & Ethical Hacking by Anupam
• 9,050 points
74 views

1 answer to this question.

0 votes

A crucial security measure is to set the Secure flag on cookies, which guarantees that cookies are only transferred over HTTPS and guards against man-in-the-middle (MITM) attacks. Here are detailed instructions for setting the Secure flag and two more boosting security flags (HttpOnly and SameSite) for Node.js and other popular server environments:

Understanding the Flags

  • Secure Flag: Forces the cookie to be transmitted only over a secure protocol (HTTPS).
  • HttpOnly Flag: Instructs the browser not to allow JavaScript to access the cookie, mitigating XSS (Cross-Site Scripting) attacks.
  • SameSite Flag: Helps protect against CSRF (Cross-Site Request Forgery) attacks by controlling whether a cookie is sent with cross-origin requests.

Setting Secure Cookies in Various Environments

Node.js (with Express)

If you're using Express, a popular Node.js web framework, you can set these flags when setting a cookie using the res.cookie() method:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    // Setting a secure cookie with HttpOnly and SameSite flags
    res.cookie('mySecureCookie', 'cookie-value', {
        secure: true, // Set the Secure flag
        httpOnly: true, // Set the HttpOnly flag
        sameSite: 'Strict', // Set the SameSite flag to Strict or Lax depending on your needs
        // maxAge: (optional) in milliseconds
    });
    res.send('Cookie set with security flags!');
});

// Ensure your server listens on HTTPS for the Secure flag to work
// For development, consider using a reverse proxy or HTTPS module like `https` with self-signed certs
const HTTPS = require('https');
const FS = require('fs');

const options = {
    key: FS.readFileSync('path/to/your/ssl/key.pem'),
    cert: FS.readFileSync('path/to/your/ssl/cert.pem')
};
const server = HTTPS.createServer(options, app);
server.listen(443, () => {
    console.log('Server listening on port 443 (HTTPS)');
});

Python (with Flask)

For Flask, a lightweight Python web framework, you can set these flags when using the set_cookie function of the response object:

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/')
def index():
    resp = make_response('Cookie set with security flags!')
    resp.set_cookie('mySecureCookie', 'cookie-value',
                    secure=True,  # Set the Secure flag
                    httponly=True,  # Set the HttpOnly flag
                    samesite='Strict')  # Set the SameSite flag
    return resp

if __name__ == '__main__':
    # For HTTPS in development, consider using a reverse proxy or tools like Flask-SSLify
    # Here, we directly run on HTTP for simplicity, but you should use HTTPS in production
    app.run(ssl_context='adhoc')  # Use 'adhoc' for a self-signed cert in development

Java (with Servlet)

In a Java Servlet environment, you can configure these flags when creating a Cookie object:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecureCookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        Cookie cookie = new Cookie("mySecureCookie", "cookie-value");
        cookie.setSecure(true); // Set the Secure flag
        cookie.setHttpOnly(true); // Set the HttpOnly flag
        // SameSite in Java Servlets is less straightforward and might require a library or manual header setting
        // For simplicity, it's omitted here but consider implementing for CSRF protection
        resp.addCookie(cookie);
        resp.getWriter().println("Cookie set with security flags!");
    }
}

Setting SameSite in Java Servlets

Since directly setting SameSite on a Cookie object in Java Servlets isn't as straightforward as other flags, you might need to manually set the Set-Cookie header. Here's a simplified approach for setting SameSite:

resp.setHeader("Set-Cookie", "mySecureCookie=cookie-value; Secure; HttpOnly; SameSite=Strict");

answered Nov 13, 2024 by CaLLmeDaDDY
• 13,760 points

Related Questions In Cyber Security & Ethical Hacking

0 votes
1 answer
0 votes
1 answer

how to know the white hat hacking?

White Hat Hacking is another name for Ethical ...READ MORE

answered Jul 23, 2019 in Cyber Security & Ethical Hacking by Ritu
1,012 views
+3 votes
1 answer

How to send the phishing link to friend?

The Social Engineer Toolkit (SET) is a ...READ MORE

answered Feb 6, 2020 in Cyber Security & Ethical Hacking by anonymous
1 flag 4,021 views
+1 vote
1 answer

How do you decrypt a ROT13 encryption on the terminal itself?

Yes, it's possible to decrypt a ROT13 ...READ MORE

answered Oct 17, 2024 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 13,760 points
181 views
+1 vote
1 answer

How does the LIMIT clause in SQL queries lead to injection attacks?

The LIMIT clause in SQL can indeed ...READ MORE

answered Oct 17, 2024 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 13,760 points
344 views
+1 vote
1 answer

Is it safe to use string concatenation for dynamic SQL queries in Python with psycopg2?

The use of string concatenation while building ...READ MORE

answered Oct 17, 2024 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 13,760 points
188 views
+1 vote
1 answer
0 votes
1 answer

How to set private DNS on Android?

Here's a step-by-step guide to help you ...READ MORE

answered Nov 27, 2024 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 13,760 points
45 views
0 votes
1 answer

How to turn off the camera light on a laptop?

Here are general steps and specific instructions ...READ MORE

answered Nov 28, 2024 in Cyber Security & Ethical Hacking by CaLLmeDaDDY
• 13,760 points
58 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP