Home > Article > Web Front-end > Sample code sharing for Node.js to set up multi-domain name whitelist in CORS cross-domain requests
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数据
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');
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 === '*') { // allow any origin headers.push([{ key: 'Access-Control-Allow-Origin', value: '*' }]); } else if (isString(options.origin)) { // fixed origin headers.push([{ key: 'Access-Control-Allow-Origin', value: options.origin }]); headers.push([{ key: 'Vary', value: 'Origin' }]); } else { isAllowed = isOriginAllowed(requestOrigin, options.origin); // reflect origin headers.push([{ key: 'Access-Control-Allow-Origin', value: isAllowed ? requestOrigin : false }]); headers.push([{ key: 'Vary', value: 'Origin' }]); } return headers; } function configureMethods(options) { var methods = options.methods; if (methods.join) { methods = options.methods.join(','); // .methods is an array, so turn it into a string } return { key: 'Access-Control-Allow-Methods', value: methods }; } function configureCredentials(options) { if (options.credentials === true) { return { key: 'Access-Control-Allow-Credentials', value: 'true' }; } return null; } function configureAllowedHeaders(options, req) { var allowedHeaders = options.allowedHeaders || options.headers; var headers = []; if (!allowedHeaders) { allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers headers.push([{ key: 'Vary', value: 'Access-Control-Request-Headers' }]); } else if (allowedHeaders.join) { allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string } if (allowedHeaders && allowedHeaders.length) { headers.push([{ key: 'Access-Control-Allow-Headers', value: allowedHeaders }]); } return headers; } function configureExposedHeaders(options) { var headers = options.exposedHeaders; if (!headers) { return null; } else if (headers.join) { headers = headers.join(','); // .headers is an array, so turn it into a string } if (headers && headers.length) { return { key: 'Access-Control-Expose-Headers', value: headers }; } return null; } function configureMaxAge(options) { var maxAge = options.maxAge && options.maxAge.toString(); if (maxAge && maxAge.length) { return { key: 'Access-Control-Max-Age', 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 === 'Vary' && 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 === 'OPTIONS') { // 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 !== 'function') { 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 === 'function') { 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 === 'function') { 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; }());
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 = [ // 域名白名单 '*.233.666.com', 'hello.world.com', 'hello..*.com' ]; app.post('a/b', 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('Access-Control-Allow-Credentials', 'true'); // 你的业务代码逻辑代码 ... // ... } else { res.send({ code: -2, msg: '非法请求' }); } });
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!