javascript 在 Mocha 和 SuperTest 中设置 Basic Auth

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28756543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:30:24  来源:igfitidea点击:

Setting Basic Auth in Mocha and SuperTest

javascriptnode.jsmochabasic-authenticationsupertest

提问by Peter Chappy

I'm trying to set us a test to verify the username and password of a path blocked by the basic auth of a username and password.

我正在尝试为我们设置一个测试,以验证被用户名和密码的基本身份验证阻止的路径的用户名和密码。

it('should receive a status code of 200 with login', function(done) {
    request(url)
        .get("/staging")
        .expect(200)
        .set('Authorization', 'Basic username:password')
        .end(function(err, res) {
            if (err) {
                throw err;
            }

            done();
        });
});

回答by Yves M.

Using the auth method

使用 auth 方法

SuperTestis based on SuperAgentwhich provides the authmethod to facilitate Basic Authentication:

SuperTest基于SuperAgent,它提供了auth方法来促进基本身份验证

it('should receive a status code of 200 with login', function(done) {
    request(url)
        .get('/staging')
        .auth('the-username', 'the-password')
        .expect(200, done);
});

Source: http://visionmedia.github.io/superagent/#basic-authentication

来源:http: //visionmedia.github.io/superagent/#basic-authentication



PS: You can pass donestraight to any of the .expect()calls

PS:您可以done直接传递给任何.expect()调用

回答by pretorh

The username:passwordpart must be base64 encoded

username:password部分必须是 base64 编码的

You can use something like

你可以使用类似的东西

.set("Authorization", "basic " + new Buffer("username:password").toString("base64"))