问题信息
我正在使用cors来确保只有特定IP才能在我的REST API中GET
和POST
上的数据。
每当有人想要GET
或POST
数据时,返回的IP是托管应用程序的服务器的IP,而不是该人自己的IP地址。
此刻,每个人都可以访问REST API,因为我的前端在同一服务器上运行,因此前端需要具有GET
和POST
数据的权限,因此我将白名单服务器的IP地址。
由于每个尝试连接的人,其ip地址自动是服务器的地址,因此每个人都可以访问REST API。
技术信息
我的REST API在端口8080上使用pm2运行,我使用Nginx将其重新路由到使用SSL的端口8877。 8877是我的其余api的终结点,也许这就是为什么客户端ip地址自动是服务器的ip地址的原因?
# General HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name www.example.com default_server;
location / {
return 302 https://$host$request_uri;
}
}
#Web Application
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name www.example.com default_server;
root /var/www/example.com;
index index.html;
ssl_stapling on;
ssl_stapling_verify on;
ssl_certificate /etc/nginx/ssl/example.com/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
#...
try_files $uri $uri/ /index.html$is_args$args;
#...
}
}
#Rest API http to https
server {
listen 8877 ssl;
listen [::]:8877 ssl;
server_name example.com;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
ssl_stapling on;
ssl_stapling_verify on;
ssl_certificate /etc/nginx/ssl/example.com/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
proxy_pass http://example.com:8080;
}
}
Rest API核心
const whitelist = [
'::ffff:111.11.11.111', etc.];
var corsOptions = {
origin: (origin, callback) => {
let trafficAllowed = {};
console.log("IP: ", origin);
if (whitelist.indexOf(origin) !== -1) {
trafficAllowed = {origin: false}
} else {
trafficAllowed = {origin: true}
}
callback(null, trafficAllowed)
}
};
app.use((req, res, next) => {
req.headers.origin =
req.connection.remoteAddress ||
req.headers['x-forwarded-for'] ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
next();
});
app.use(cors(corsOptions));
可能的解决方法
答案 0 :(得分:0)
尝试将这些配置放入您的nginx:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
否则,您的后端将仅接收nginx IP地址。