2018-10-10 16:19:509549人阅读
https://example.com/login?url=http://examp1e.com/bad/things
var express = require('express');
var port = process.env.PORT || 3000;
var app = express();
app.get('/login', function (req, res, next) {
if(req.session.isAuthenticated()) {
res.redirect(req.query.url);
}
});
app.get('/account', function (req, res, next) {
res.send('Account page');
});
app.get('/profile', function (req, res, next) {
res.send('Profile page');
});
app.listen(port, function() {
console.log('Server listening on port ' + port);
});//Configure your whitelist
var baseHostname = "https://example.com";
var redirectMapping = {
'account': '/account',
'profile': '/profile'
}
//Create a function to validate whitelist
function validateRedirect(key) {
if(key in redirectMapping) {
return redirectMapping[key];
}else{
return false;
}
}
app.get('/login', function (req, res, next) {
if(req.session.isAuthenticated()) {
redirectPath = validateRedirect(req.query.url);
if(redirectPath) {
res.redirect(encodeURI(baseHostname + redirectPath));
}else{
res.send('Not a valid redirect!');
}
}
});//Configure your whitelist
var baseHostname = "https://example.com";
app.get('/login', function (req, res, next) {
productId = (req.query.productId || '');
whitelistRegEx = /^[a-zA-Z0-9]{16}$/;
if(productId) {
//Validate the productId is alphanumeric and exactly 16 characters
if(whitelistRegEx.test(productId)) {
res.redirect(encodeURI(baseHostname + '/item/' + productId));
}else{
//The productId did not meet the RegEx whitelist, so return an error
res.send('Invalid product ID');
}
}else{
//No productId was provided, so redirect to home page
res.redirect('/');
}
});本文翻译自:https://blog.hailstone.io/how-to-prevent-unsafe-redirects-in-node-js
翻译作者:lucywang 原文地址: http://www.4hou.com/web/13899.html