带Lambda授权的POST接口在Postman可用但前端报403权限错误
问题分析与解决方案
核心问题
前端请求的Authorization头自带了Bearer 前缀,但Lambda授权器直接将请求头的值与纯token字符串做对比,导致匹配失败返回403。另外需注意API Gateway传递给Lambda的headers键名可能存在大小写差异,直接用固定键名取值也可能引发错误。
修复步骤
1. 修改Lambda授权器代码
调整逻辑,先提取Authorization头里的实际token(去掉Bearer 前缀),同时兼容headers键名的大小写:
import json def lambda_handler(event, context): # 兼容headers键名的大小写,优先取Authorization,再取authorization auth_header = event['headers'].get('Authorization') or event['headers'].get('authorization') if auth_header: # 提取Bearer前缀后的token内容 token = auth_header.split(' ')[-1] if token == 'secretcode': return { "isAuthorized": True, "context": { "anyotherparam": "values" } } # 未通过授权的情况 return { "isAuthorized": False, "context": { "anyotherparam": "values" } }
2. 前端代码优化(可选但推荐)
发送JSON数据时,建议添加Content-Type: application/json请求头,确保API Gateway能正确解析请求体:
function addSlots() { var response = ""; var jsonData = new Object(); jsonData.restaurant_name_date_time = document.getElementById("date_time_slot").value; jsonData.number_of_pax = document.getElementById("number_of_pax_2").value; jsonData.restaurant_name = document.getElementById("restaurant_name_slot").value; var access_token = document.getElementById("access_token").value; console.log(jsonData, access_token) var request = new XMLHttpRequest(); request.open("POST", "https://skdsdjakand.execute-api.us-east-1.amazonaws.com/slots", true); request.setRequestHeader("Authorization", "Bearer " + access_token); // 添加Content-Type头,确保JSON格式被正确识别 request.setRequestHeader("Content-Type", "application/json"); request.onload = function () { response = JSON.parse(request.responseText); console.log(response) if (response.message == "slot added") { alert('恭喜!时段添加成功'); } else if (response.message == "forbidden") { alert('无效令牌,请输入有效的访问令牌'); } else { alert('错误,无法添加时段'); } }; request.send(JSON.stringify(jsonData)); }
验证逻辑
修改后,前端发送的Authorization: Bearer secretcode会被Lambda提取出secretcode,与预设值匹配后授权通过;同时兼容了headers键名的大小写问题,避免因键名不一致导致的取值错误。
内容的提问来源于stack exchange,提问作者lalala
相关产品推荐
相关产品推荐

