usage.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Load modules
  2. var Http = require('http');
  3. var Request = require('request');
  4. var Hawk = require('../lib');
  5. // Declare internals
  6. var internals = {
  7. credentials: {
  8. dh37fgj492je: {
  9. id: 'dh37fgj492je', // Required by Hawk.client.header
  10. key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
  11. algorithm: 'sha256',
  12. user: 'Steve'
  13. }
  14. }
  15. };
  16. // Credentials lookup function
  17. var credentialsFunc = function (id, callback) {
  18. return callback(null, internals.credentials[id]);
  19. };
  20. // Create HTTP server
  21. var handler = function (req, res) {
  22. Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
  23. var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');
  24. var headers = {
  25. 'Content-Type': 'text/plain',
  26. 'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })
  27. };
  28. res.writeHead(!err ? 200 : 401, headers);
  29. res.end(payload);
  30. });
  31. };
  32. Http.createServer(handler).listen(8000, '127.0.0.1');
  33. // Send unauthenticated request
  34. Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {
  35. console.log(response.statusCode + ': ' + body);
  36. });
  37. // Send authenticated request
  38. credentialsFunc('dh37fgj492je', function (err, credentials) {
  39. var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });
  40. var options = {
  41. uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',
  42. method: 'GET',
  43. headers: {
  44. authorization: header.field
  45. }
  46. };
  47. Request(options, function (error, response, body) {
  48. var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
  49. console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));
  50. process.exit(0);
  51. });
  52. });