Basic authentication 如何使用gulp browser sync为web服务器启用基本身份验证?
我们的web应用程序正在使用需要基本身份验证的RESTAPI 我想这样编写浏览器同步吞咽任务:Basic authentication 如何使用gulp browser sync为web服务器启用基本身份验证?,basic-authentication,gulp,Basic Authentication,Gulp,我们的web应用程序正在使用需要基本身份验证的RESTAPI 我想这样编写浏览器同步吞咽任务: gulp.task('browser-sync', function() { browserSync({ server: { baseDir: './' }, authenticate: 'authentication-token-here-djfhjsdfjsgdf' }); }); 如何配置此功能?您可以使用
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: './'
},
authenticate: 'authentication-token-here-djfhjsdfjsgdf'
});
});
如何配置此功能?您可以使用处理每个请求的
中间件
选项轻松完成此操作:
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: './'
},
middleware: [
function(req, res, next) {
const user = 'user';
const pass = 'pass';
let authorized = false;
// See if authorization exist in the request and matches username/password
if (req.headers.authorization) {
const credentials = new Buffer(req.headers.authorization.replace('Basic ', ''), 'base64').toString().split(/:(.*)/)
if (credentials[0] === user && credentials[1] === pass) {
authorized = true;
}
}
if (authorized) {
// Proceed to fulfill the request
next();
} else {
// Authorization doesn't exist / doesn't match, send authorization request in the response header
res.writeHead(401, {'WWW-Authenticate': 'Basic realm="Authenticate"'})
res.end();
}
}
]
});
});