Guest User

Serverless Authentication

a guest
Apr 26th, 2019
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2. exports.handler = (event, context, callback) => {
  3.  
  4.     // Get request and request headers
  5.     const request = event.Records[0].cf.request;
  6.     const headers = request.headers;
  7.  
  8.     // Configure authentication
  9.     const authUser = 'user';
  10.     const authPass = 'pass';
  11.  
  12.     // Construct the Basic Auth string
  13.     const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');
  14.  
  15.     // Require Basic authentication
  16.     if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
  17.         const body = 'Unauthorized';
  18.         const response = {
  19.             status: '401',
  20.             statusDescription: 'Unauthorized',
  21.             body: body,
  22.             headers: {
  23.                 'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
  24.             },
  25.         };
  26.         callback(null, response);
  27.     }
  28.  
  29.     // Continue request processing if authentication passed
  30.     callback(null, request);
  31. };
Add Comment
Please, Sign In to add comment