forked from request/request
/
test-basic-auth.js
66 lines (57 loc) · 1.52 KB
/
test-basic-auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var assert = require('assert')
, http = require('http')
, request = require('../main')
;
var numBasicRequests = 0;
var basicServer = http.createServer(function (req, res) {
console.error('Basic auth server: ', req.method, req.url);
numBasicRequests++;
var ok;
if (req.headers.authorization) {
if (req.headers.authorization == 'Basic ' + new Buffer('test:testing2').toString('base64')) {
ok = true;
} else {
// Bad auth header, don't send back WWW-Authenticate header
ok = false;
}
} else {
// No auth header, send back WWW-Authenticate header
ok = false;
res.setHeader('www-authenticate', 'Basic realm="Private"');
}
if (ok) {
console.log('request ok');
res.end('ok');
} else {
console.log('status=401');
res.statusCode = 401;
res.end('401');
}
});
basicServer.listen(6767);
request({
'method': 'GET',
'uri': 'http://localhost:6767/test/',
'auth': {
'user': 'test',
'pass': 'testing2',
'sendImmediately': false
}
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numBasicRequests, 2);
// If we don't set sendImmediately = false, request will send basic auth
request({
'method': 'GET',
'uri': 'http://localhost:6767/test2/',
'auth': {
'user': 'test',
'pass': 'testing2'
}
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numBasicRequests, 3);
console.log('All tests passed');
basicServer.close();
});
});