Home Web Front-end JS Tutorial Sample code sharing for Node.js to set up multi-domain name whitelist in CORS cross-domain requests

Sample code sharing for Node.js to set up multi-domain name whitelist in CORS cross-domain requests

Mar 28, 2017 pm 02:34 PM

This article mainly introduces Node.js How to set up a multi-domain name whitelist in CORS cross-domain requests. The article introduces it in detail through sample code. I believe it will be useful to everyone. It has a certain reference value. Friends who need it can take a look below.

CORS

Speaking of CORS, I believe everyone is familiar with the front end. I won’t say more here. You can read this article for details. article.

CORS mainly configures the Access-Control-Allow-Origin attribute in the Response header to the domain name that you allow the interface to access. The most common setting is:

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', 'true'); // 允许服务器端发送Cookie数据
Copy after login

However, this setting is the simplest and crudest, and it is also the least safe. It means that the interface allows all domain names to make cross-domain requests to it. However, in general actual business, it is expected that the interface only allows cross-domain request permissions to be opened to one or a few websites, not all.

So, if you are smart, you must be thinking, isn’t it easy to whitelist multiple domain names? Just write a regular rule? If that doesn't work, wouldn't it be better to directly configure the Access-Control-Allow-Origin attribute to multiple domain names separated by commas?

Like the following:

res.header('Access-Control-Allow-Origin', '*.666.com'); 

// 或者如下
res.header('Access-Control-Allow-Origin', 'a.666.com,b.666.com,c.666.com');
Copy after login

I'm sorry to tell you that this way of writing is invalid. In Node.js, the Access-Control-Allow-Origin attribute in the res response header cannot match regular expressions except (*), and domain names cannot be separated by commas. In other words, the attribute value of Access-Control-Allow-Origin is only allowed to be set to a single determined domain name string or (*).

Since we want to allow multiple domain names and are not willing to use unsafe * wildcards, is it really impossible to configure CORS for multiple domain name whitelists?

CORS with multiple domain name whitelists is indeed achievable. It just has a bit of a twist to save the country.

CORS implementation principle of multi-domain whitelist

For specific principles, please refer to the core code of the cors library:

(function () {

 'use strict';

 var assign = require('object-assign');
 var vary = require('vary');

 var defaults = {
 origin: '*',
 methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
 preflightContinue: false,
 optionsSuccessStatus: 204
 };

 function isString(s) {
 return typeof s === 'string' || s instanceof String;
 }

 function isOriginAllowed(origin, allowedOrigin) {
 if (Array.isArray(allowedOrigin)) {
 for (var i = 0; i < allowedOrigin.length; ++i) {
 if (isOriginAllowed(origin, allowedOrigin[i])) {
  return true;
 }
 }
 return false;
 } else if (isString(allowedOrigin)) {
 return origin === allowedOrigin;
 } else if (allowedOrigin instanceof RegExp) {
 return allowedOrigin.test(origin);
 } else {
 return !!allowedOrigin;
 }
 }

 function configureOrigin(options, req) {
 var requestOrigin = req.headers.origin,
 headers = [],
 isAllowed;

 if (!options.origin || options.origin === &#39;*&#39;) {
 // allow any origin
 headers.push([{
 key: &#39;Access-Control-Allow-Origin&#39;,
 value: &#39;*&#39;
 }]);
 } else if (isString(options.origin)) {
 // fixed origin
 headers.push([{
 key: &#39;Access-Control-Allow-Origin&#39;,
 value: options.origin
 }]);
 headers.push([{
 key: &#39;Vary&#39;,
 value: &#39;Origin&#39;
 }]);
 } else {
 isAllowed = isOriginAllowed(requestOrigin, options.origin);
 // reflect origin
 headers.push([{
 key: &#39;Access-Control-Allow-Origin&#39;,
 value: isAllowed ? requestOrigin : false
 }]);
 headers.push([{
 key: &#39;Vary&#39;,
 value: &#39;Origin&#39;
 }]);
 }

 return headers;
 }

 function configureMethods(options) {
 var methods = options.methods;
 if (methods.join) {
 methods = options.methods.join(&#39;,&#39;); // .methods is an array, so turn it into a string
 }
 return {
 key: &#39;Access-Control-Allow-Methods&#39;,
 value: methods
 };
 }

 function configureCredentials(options) {
 if (options.credentials === true) {
 return {
 key: &#39;Access-Control-Allow-Credentials&#39;,
 value: &#39;true&#39;
 };
 }
 return null;
 }

 function configureAllowedHeaders(options, req) {
 var allowedHeaders = options.allowedHeaders || options.headers;
 var headers = [];

 if (!allowedHeaders) {
 allowedHeaders = req.headers[&#39;access-control-request-headers&#39;]; // .headers wasn&#39;t specified, so reflect the request headers
 headers.push([{
 key: &#39;Vary&#39;,
 value: &#39;Access-Control-Request-Headers&#39;
 }]);
 } else if (allowedHeaders.join) {
 allowedHeaders = allowedHeaders.join(&#39;,&#39;); // .headers is an array, so turn it into a string
 }
 if (allowedHeaders && allowedHeaders.length) {
 headers.push([{
 key: &#39;Access-Control-Allow-Headers&#39;,
 value: allowedHeaders
 }]);
 }

 return headers;
 }

 function configureExposedHeaders(options) {
 var headers = options.exposedHeaders;
 if (!headers) {
 return null;
 } else if (headers.join) {
 headers = headers.join(&#39;,&#39;); // .headers is an array, so turn it into a string
 }
 if (headers && headers.length) {
 return {
 key: &#39;Access-Control-Expose-Headers&#39;,
 value: headers
 };
 }
 return null;
 }

 function configureMaxAge(options) {
 var maxAge = options.maxAge && options.maxAge.toString();
 if (maxAge && maxAge.length) {
 return {
 key: &#39;Access-Control-Max-Age&#39;,
 value: maxAge
 };
 }
 return null;
 }

 function applyHeaders(headers, res) {
 for (var i = 0, n = headers.length; i < n; i++) {
 var header = headers[i];
 if (header) {
 if (Array.isArray(header)) {
  applyHeaders(header, res);
 } else if (header.key === &#39;Vary&#39; && header.value) {
  vary(res, header.value);
 } else if (header.value) {
  res.setHeader(header.key, header.value);
 }
 }
 }
 }

 function cors(options, req, res, next) {
 var headers = [],
 method = req.method && req.method.toUpperCase && req.method.toUpperCase();

 if (method === &#39;OPTIONS&#39;) {
 // preflight
 headers.push(configureOrigin(options, req));
 headers.push(configureCredentials(options, req));
 headers.push(configureMethods(options, req));
 headers.push(configureAllowedHeaders(options, req));
 headers.push(configureMaxAge(options, req));
 headers.push(configureExposedHeaders(options, req));
 applyHeaders(headers, res);

 if (options.preflightContinue ) {
 next();
 } else {
 res.statusCode = options.optionsSuccessStatus || defaults.optionsSuccessStatus;
 res.end();
 }
 } else {
 // actual response
 headers.push(configureOrigin(options, req));
 headers.push(configureCredentials(options, req));
 headers.push(configureExposedHeaders(options, req));
 applyHeaders(headers, res);
 next();
 }
 }

 function middlewareWrapper(o) {
 if (typeof o !== &#39;function&#39;) {
 o = assign({}, defaults, o);
 }

 // if options are static (either via defaults or custom options passed in), wrap in a function
 var optionsCallback = null;
 if (typeof o === &#39;function&#39;) {
 optionsCallback = o;
 } else {
 optionsCallback = function (req, cb) {
 cb(null, o);
 };
 }

 return function corsMiddleware(req, res, next) {
 optionsCallback(req, function (err, options) {
 if (err) {
  next(err);
 } else {
  var originCallback = null;
  if (options.origin && typeof options.origin === &#39;function&#39;) {
  originCallback = options.origin;
  } else if (options.origin) {
  originCallback = function (origin, cb) {
  cb(null, options.origin);
  };
  }

  if (originCallback) {
  originCallback(req.headers.origin, function (err2, origin) {
  if (err2 || !origin) {
  next(err2);
  } else {
  var corsOptions = Object.create(options);
  corsOptions.origin = origin;
  cors(corsOptions, req, res, next);
  }
  });
  } else {
  next();
  }
 }
 });
 };
 }

 // can pass either an options hash, an options delegate, or nothing
 module.exports = middlewareWrapper;

}());
Copy after login

The implementation principle is as follows:

Since the Access-Control-Allow-Origin attribute has made it clear that multiple domain names cannot be set, then we have to give up this path.

The most popular and effective method is to determine on the server side whether the Origin attribute value (req.header.origin) in the requested header is in our domain name whitelist. If it is in the whitelist, then we set Access-Control-Allow-Origin to the current Origin value, which meets the single domain name requirement of Access-Control-Allow-Origin and ensures that the current request is accessed; if If it is not in the whitelist, error message will be returned.

In this way, we transfer the verification of cross-domain requests from the browser to the server. The verification of the Origin string becomes equivalent to the verification of a regular string. We can not only use arraylist verification, but also use regular matching.

The specific code is as follows:

// 判断origin是否在域名白名单列表中
function isOriginAllowed(origin, allowedOrigin) {
 if (_.isArray(allowedOrigin)) {
 for(let i = 0; i < allowedOrigin.length; i++) {
  if(isOriginAllowed(origin, allowedOrigin[i])) {
  return true;
  }
 }
 return false;
 } else if (_.isString(allowedOrigin)) {
 return origin === allowedOrigin;
 } else if (allowedOrigin instanceof RegExp) {
 return allowedOrigin.test(origin);
 } else {
 return !!allowedOrigin;
 }
}


const ALLOW_ORIGIN = [ // 域名白名单
 &#39;*.233.666.com&#39;,
 &#39;hello.world.com&#39;,
 &#39;hello..*.com&#39;
];

app.post(&#39;a/b&#39;, function (req, res, next) {
 let reqOrigin = req.headers.origin; // request响应头的origin属性

 // 判断请求是否在域名白名单内
 if(isOriginAllowed(reqOrigin, ALLOW_ORIGIN)) {
 // 设置CORS为请求的Origin值
 res.header("Access-Control-Allow-Origin", reqOrigin);
 res.header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);

 // 你的业务代码逻辑代码 ...
 // ...
 } else {
 res.send({ code: -2, msg: &#39;非法请求&#39; });
 }
});
Copy after login

Oh yeah, it’s perfect~

Summary

The above is the detailed content of Sample code sharing for Node.js to set up multi-domain name whitelist in CORS cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

See all articles