Tips and Tricks for Web Apps Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/asp-net-performance/tips-and-tricks-for-web-apps/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Mon, 23 Jun 2025 17:30:46 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.1 https://www.anujvarma.com/wp-content/uploads/anujtech.png Tips and Tricks for Web Apps Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/asp-net-performance/tips-and-tricks-for-web-apps/ 32 32 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
Concealing email on your website from web crawlers and spammers https://www.anujvarma.com/concealing-email-on-your-website-from-web-crawlers-and-spammers/ https://www.anujvarma.com/concealing-email-on-your-website-from-web-crawlers-and-spammers/#respond Thu, 08 Sep 2011 23:38:34 +0000 http://www.anujvarma.com/concealing-email-on-your-website-from-web-crawlers-and-spammers/ Say you want to display a contact email on your website – but are worried about crawlers, spammers etc. picking it up and making your life miserable. There’s a few […]

The post Concealing email on your website from web crawlers and spammers appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Say you want to display a contact email on your website – but are worried about crawlers, spammers etc. picking it up and making your life miserable. There’s a few workarounds – but this one is about as elegant as it gets. In effect, instead of writing out your email inside the mailto: tag, let some javascript code spit it out for you (javascript is good at spitting out html). Not only that – but let it construct it for you from broken up components (e.g. – for an email address = joe@joessite.com you just pass it joe, joessite and 0 – the 0 denotes a .com). The javascript will construct the full email address for you from these pieces. In effect, your actual email address is not listed ANYWHERE on the site (it is created dynamically by javascript), so there’s no chance of a crawler, spammer being able to read it.

  1. Include the following javascript (emailconcealer.js) in your file (either inline or referenced).

 

Code Snippet
  1. // EmailConcealer.js
  2.  
  3. var tld_ = new Array()
  4.  
  5. tld_[0] = "com";
  6.  
  7. tld_[1] = "org";
  8.  
  9. tld_[2] = "net";
  10.  
  11. tld_[3] = "ws";
  12.  
  13. tld_[4] = "info";
  14.  
  15. tld_[10] = "co.uk";
  16.  
  17. tld_[11] = "org.uk";
  18.  
  19. tld_[12] = "gov.uk";
  20.  
  21. tld_[13] = "ac.uk";
  22.  
  23. var topDom_ = 13;
  24.  
  25. var m_ = "mailto:";
  26.  
  27. var a_ = "@";
  28.  
  29. var d_ = ".";
  30.  
  31.  
  32. function mail2(name, dom, tl, params, display) {
  33.  
  34.     document.write('<a href="' + m_ + e(name, dom, tl) + params + '">' + display + '</a>');
  35.  
  36. }
  37.  
  38. function e(name, dom, tl) {
  39.  
  40.     var s = name + a_;
  41.  
  42.     if (tl != -2) {
  43.  
  44.         s += dom;
  45.  
  46.         if (tl >= 0)
  47.  
  48.             s += d_ + tld_[tl];
  49.  
  50.     }
  51.  
  52.     else
  53.  
  54.         s += swapper(dom);
  55.  
  56.     return s;
  57.  
  58. }
  59.  
  60. function swapper(d) {
  61.  
  62.     var s = "";
  63.  
  64.     for (var i = 0; i < d.length; i += 2)
  65.  
  66.         if (i + 1 == d.length)
  67.  
  68.             s += d.charAt(i)
  69.  
  70.         else
  71.  
  72.             s += d.charAt(i + 1) + d.charAt(i);
  73.  
  74.     return s.replace(/\?/g, '.');

 

2.  If you are inside an ASP.NET content page (or master page), you will need to reference the script within the Page_Load of the content page (or master page). Otherwise, proceed to step 3.

Code Snippet
  1. protected void Page_Load(object sender, EventArgs e)
  2.     {
  3.         Page.ClientScript.RegisterClientScriptInclude(“selective”, ResolveUrl(@”scripts\emailconcealer.js”));
  4.         if (!Master.Page.ClientScript.IsStartupScriptRegistered(“alert”))
  5.         {
  6.             Master.Page.ClientScript.RegisterStartupScript
  7.                 (this.GetType(), “alert”, “insideJS();”, true);
  8.         }
  9.     }

3. Insert the following <script> code in your aspx (web page)

Email: <script type=”text/javascript”>mail2(“joe”, “joessite”, 0, “”, “Contact Joe”)</script>

See an example in action

See the email link on my contact form on this website for a live example.

http://cut.ms/bne8

Summary

Don’t be intimidated by spammers, crawlers into hiding your email address on your website. There’s a way to have your cake (put your email link) and eat it too (not let crawlers decipher it).

The post Concealing email on your website from web crawlers and spammers appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/concealing-email-on-your-website-from-web-crawlers-and-spammers/feed/ 0