如何使用gulp browser-sync为Web服务器启用基本身份验证?

问题描述 投票:7回答:1

我们的Web应用程序正在使用需要基本身份验证的REST API。

我想写这样的browser-sync gulp任务:

gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: './'
        },
        authenticate: 'authentication-token-here-djfhjsdfjsgdf'
    });
});

怎么配置这个?

basic-authentication gulp
1个回答
0
投票

您可以使用处理每个请求的middleware选项轻松完成:

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();
                }
            }

        ]
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.