CORS 仅阻止本地主机请求
CORS block only localhost request
我用 EXPRESS 开发并托管在 NGINX 上的服务器有问题。
我使用 passport.js 进行用户身份验证,即使我不认为这是问题所在,当我尝试从本地主机登录时出现错误,而如果我 运行将它上传到我的域我没有弄错并且它工作正常,所以我认为这是阻止本地主机请求的 CORS 问题。
NGINX 默认值
server {
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name api.mysite.com www.api.mysite.com;
location / {
proxy_pass https://localhost:3007; #whatever port your app runs on
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
if ($http_origin ~* (^https?://([^/]+\.)*(mysite)\.com$)) {
set $cors "true";
}
if ($http_origin ~* (^http?://([^/]+\.)*(localhost:3006))) {
set $cors "true";
}
if ($http_origin ~* (^https?://([^/]+\.)*(192.168.1.21:3006))) {
set $cors "true";
}
# Nginx doesn't support nested If statements. This is where things get slightly nasty.
# Determine the HTTP request method used
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
if ($cors = "true") {
# Catch all incase there's a request method we're not dealing with properly
add_header 'Access-Control-Allow-Origin' "$http_origin";
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($cors = "trueoptions") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($cors = "truepost") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
serverDev.js
const sessionParser = session({
saveUninitialized: false,
secret: 'secret',
resave: false,
cookie: {expires: 43200000, secure: false }
})
var privateKey = fs.readFileSync('ssl-cert/privkey.pem', 'utf8');
var certificate = fs.readFileSync('ssl-cert/fullchain.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var httpsServer = https.createServer(credentials,app);
routes.js
app.post('/Login', passport.authenticate('local-login', {
successRedirect : '/Profile',
failureRedirect : '/Login',
failureFlash : false
}),
function(req, res) {
if (req.body.remember) {
req.session.cookie.maxAge = 1000 * 60 * 3;
} else {
req.session.cookie.expires = false;
}
res.redirect('/Login');
});
app.get('/Profile', isLoggedIn, todoList.profile);
function isLoggedIn(req, res, next) {
console.log("isLoggedIn",req.isAuthenticated()) <--- THIS IS THE PROBLEM IN LOCALHOST RETURN ALWAYS FALSE
if (req.isAuthenticated())
return next();
res.redirect('/Login');
}
passport.js
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("use `Users`");
connection.query("SELECT * FROM Accounts WHERE id = ? ",[id], function(err, rows){
if (err){
return done(err);
}
var user = rows[0];
done(err, user);
});
});
如果其他人有这个问题,我通过以这种方式配置'express-session'
解决了它
var session = require('express-session');
const sessionParser = session({
secret: 'your-secret',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'none',
maxAge: 1000 * 60 * 60 * 12 // milliseconds * seconds * minutes * hours
}
})
我用 EXPRESS 开发并托管在 NGINX 上的服务器有问题。
我使用 passport.js 进行用户身份验证,即使我不认为这是问题所在,当我尝试从本地主机登录时出现错误,而如果我 运行将它上传到我的域我没有弄错并且它工作正常,所以我认为这是阻止本地主机请求的 CORS 问题。
NGINX 默认值
server {
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name api.mysite.com www.api.mysite.com;
location / {
proxy_pass https://localhost:3007; #whatever port your app runs on
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
if ($http_origin ~* (^https?://([^/]+\.)*(mysite)\.com$)) {
set $cors "true";
}
if ($http_origin ~* (^http?://([^/]+\.)*(localhost:3006))) {
set $cors "true";
}
if ($http_origin ~* (^https?://([^/]+\.)*(192.168.1.21:3006))) {
set $cors "true";
}
# Nginx doesn't support nested If statements. This is where things get slightly nasty.
# Determine the HTTP request method used
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
if ($cors = "true") {
# Catch all incase there's a request method we're not dealing with properly
add_header 'Access-Control-Allow-Origin' "$http_origin";
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($cors = "trueoptions") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($cors = "truepost") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
serverDev.js
const sessionParser = session({
saveUninitialized: false,
secret: 'secret',
resave: false,
cookie: {expires: 43200000, secure: false }
})
var privateKey = fs.readFileSync('ssl-cert/privkey.pem', 'utf8');
var certificate = fs.readFileSync('ssl-cert/fullchain.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var httpsServer = https.createServer(credentials,app);
routes.js
app.post('/Login', passport.authenticate('local-login', {
successRedirect : '/Profile',
failureRedirect : '/Login',
failureFlash : false
}),
function(req, res) {
if (req.body.remember) {
req.session.cookie.maxAge = 1000 * 60 * 3;
} else {
req.session.cookie.expires = false;
}
res.redirect('/Login');
});
app.get('/Profile', isLoggedIn, todoList.profile);
function isLoggedIn(req, res, next) {
console.log("isLoggedIn",req.isAuthenticated()) <--- THIS IS THE PROBLEM IN LOCALHOST RETURN ALWAYS FALSE
if (req.isAuthenticated())
return next();
res.redirect('/Login');
}
passport.js
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("use `Users`");
connection.query("SELECT * FROM Accounts WHERE id = ? ",[id], function(err, rows){
if (err){
return done(err);
}
var user = rows[0];
done(err, user);
});
});
如果其他人有这个问题,我通过以这种方式配置'express-session'
解决了它
var session = require('express-session');
const sessionParser = session({
secret: 'your-secret',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'none',
maxAge: 1000 * 60 * 60 * 12 // milliseconds * seconds * minutes * hours
}
})