Reputation: 360
I associated the following AWS Lambda function with CloudFront to add authentication to a static website hosted in Amazon S3, the problem with the for loop, if I test against a single username and password it works fine, If I add multiple credentials I got 503 Error.
exports.handler = (event, context, callback) => {
// Get request and request headers
const request = event.Records[0].cf.request;
const headers = request.headers;
// Configure authentication
const credentials = {
'admin1': 'passadmin2',
'user1': 'passuser1',
'admin2': 'passadmin2',
'user2': 'passuser2'
};
let authenticated = true;
//verify the Basic Auth string
for (let username in credentials) {
// Build a Basic Authentication string
let authString = 'Basic ' + Buffer.from(username + ':' + credentials[username]).toString('base64');
if (headers.authorization[0].value == authString) {
// User has authenticated
authenticated = true;
}
}
// Require Basic authentication
if (typeof headers.authorization == 'undefined' || !authenticated) {
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);
};
With one single username and password, it works just fine :
Example :
exports.handler = (event, context, callback) => {
// Get the request and its headers
const request = event.Records[0].cf.request;
const headers = request.headers;
// Specify the username and password to be used
const user = 'admin1';
const pw = 'passadmin1';
// Build a Basic Authentication string
const authString = 'Basic ' + new Buffer(user + ':' + pw).toString('base64');
// Challenge for auth if auth credentials are absent or incorrect
if (typeof headers.authorization == 'undefined' || headers.authorization[0].value != authString) {
const response = {
status: '401',
statusDescription: 'Unauthorized',
body: 'Unauthorized',
headers: {
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
},
};
callback(null, response);
}
// User has authenticated
callback(null, request);
};
I'm using nodejs 8 and typescript for this function. Could anyone please tell me what's wrong with the first function ?
Upvotes: 0
Views: 913
Reputation: 7417
You are checking headers.authorization[0]
without checking that it is not undefined:
It should be:
...
if (headers.authorization && headers.authorization[0].value == authString) {
// User has authenticated
authenticated = true;
}
...
Upvotes: 3