Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81146 views
1
// Load modules
2
3
var Http = require('http');
4
var Request = require('request');
5
var Hawk = require('../lib');
6
7
8
// Declare internals
9
10
var internals = {
11
credentials: {
12
dh37fgj492je: {
13
id: 'dh37fgj492je', // Required by Hawk.client.header
14
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
15
algorithm: 'sha256',
16
user: 'Steve'
17
}
18
}
19
};
20
21
22
// Credentials lookup function
23
24
var credentialsFunc = function (id, callback) {
25
26
return callback(null, internals.credentials[id]);
27
};
28
29
30
// Create HTTP server
31
32
var handler = function (req, res) {
33
34
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
35
36
var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
37
var headers = {
38
'Content-Type': 'text/plain',
39
'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })
40
};
41
42
res.writeHead(!err ? 200 : 401, headers);
43
res.end(payload);
44
});
45
};
46
47
Http.createServer(handler).listen(8000, '127.0.0.1');
48
49
50
// Send unauthenticated request
51
52
Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {
53
54
console.log(response.statusCode + ': ' + body);
55
});
56
57
58
// Send authenticated request
59
60
credentialsFunc('dh37fgj492je', function (err, credentials) {
61
62
var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });
63
var options = {
64
uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',
65
method: 'GET',
66
headers: {
67
authorization: header.field
68
}
69
};
70
71
Request(options, function (error, response, body) {
72
73
var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
74
console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
75
process.exit(0);
76
});
77
});
78
79
80