Skip to content

Instantly share code, notes, and snippets.

@iza-w
Forked from lmakarov/lambda-basic-auth.js
Created October 7, 2020 19:14
Show Gist options
  • Save iza-w/c0c456d11a93c5220ad2161f30374cba to your computer and use it in GitHub Desktop.
Save iza-w/c0c456d11a93c5220ad2161f30374cba to your computer and use it in GitHub Desktop.

Revisions

  1. Leonid Makarov created this gist Aug 30, 2017.
    31 changes: 31 additions & 0 deletions lambda-basic-auth.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    'use strict';
    exports.handler = (event, context, callback) => {

    // Get request and request headers
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    // Configure authentication
    const authUser = 'user';
    const authPass = 'pass';

    // Construct the Basic Auth string
    const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');

    // Require Basic authentication
    if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
    const body = 'Unauthorized';
    const response = {
    status: '401',
    statusDescription: 'Unauthorized',
    body: body,
    headers: {
    'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
    },
    };
    callback(null, response);
    }

    // Continue request processing if authentication passed
    callback(null, request);
    };