amazon-web-services - 使用 Cloudfront 和 AWS Lambda 对 S3 托管网站进行身份验证时出现 503 错误
问题描述
我将以下AWS Lambda 函数与CloudFront相关联,以向托管在Amazon S3中的静态网站添加身份验证,for 循环的问题,如果我针对单个用户名和密码进行测试,它工作正常,如果我添加多个凭证,我得到 503 错误.
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);
};
只需一个用户名和密码,它就可以正常工作:
例子 :
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);
};
我正在使用 nodejs 8 和 typescript 来实现这个功能。谁能告诉我第一个功能有什么问题?
解决方案
您正在检查headers.authorization[0]
而不检查它是否未定义:
它应该是:
...
if (headers.authorization && headers.authorization[0].value == authString) {
// User has authenticated
authenticated = true;
}
...
推荐阅读
- android - Android Studio MySql 登录
- redirect - 防止 API URL 重定向。(Nginx - 网站重定向)
- javascript - Firebase Cloud Functions 的超时效率
- c - cmake头文件包含来自静态库
- java - 在 java 中测试 zip 文件的上传会引发 EOFException
- ldap - openldap:使用 ldapadd 添加用户失败
- android - Android Studio如何正确地将listview项目插入sqlite数据库
- vue.js - Vuetify Autocomplete, item-slot , 保持字符高亮
- python - 在 APScheduler 中超出计划的手动作业执行
- python - SQLite 按行/列获取项目