AWS Lambda函数中REST API Basic Auth认证失败求助
问题:AWS Lambda中调用REST API的Basic认证失败(本地PyCharm运行正常)
示例代码
import json import os import sys import logging import argparse import re import requests import pandas as pd import boto3 import datetime import time import base64 import xml.etree.ElementTree as ET def lambda_handler(event, context): head = { 'Content-Type': 'application/xml', 'Authorization': 'c2Vn6Z1oxK3R3Q18=' } body = f"""<?xml version='1.0' encoding='UTF-8' ?> <ServiceRequest> <filters> </filters> <preferences> <startFromOffset>1</startFromOffset> <limitResults>1</limitResults> </preferences> </ServiceRequest>""" request_URL='https:' response = requests.post(request_URL, headers=head, data=body) print(response.text) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') }
返回错误信息
<?xml version="1.0" encoding="UTF-8"?> <ServiceResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https:"> <responseCode>INVALID_CREDENTIALS</responseCode> <responseErrorDetails> <errorMessage>HTTP BASIC AUTH header is malformed.</errorMessage> </responseErrorDetails> </ServiceResponse>
排查方案
- 检查Authorization头格式:Basic认证规范要求头值必须以
Basic(含空格)为前缀,后跟base64编码的用户名:密码字符串。确认本地代码的Authorization头是否带了该前缀,若本地有但Lambda代码漏加,补上即可。 - 验证base64字符串有效性:在Lambda代码中添加解码验证,打印解码结果确认是否为正确的
用户名:密码格式(必须包含冒号):
对比本地解码结果,排除编码差异。print(base64.b64decode('c2Vn6Z1oxK3R3Q18=').decode('utf-8')) - 改用requests内置auth参数:避免手动构造头的失误,用requests的
HTTPBasicAuth自动生成合规的认证头:from requests.auth import HTTPBasicAuth # 移除head中的Authorization字段,改用auth参数 response = requests.post( request_URL, headers={'Content-Type': 'application/xml'}, data=body, auth=HTTPBasicAuth('你的用户名', '你的密码') ) - 核对依赖版本一致性:检查Lambda与本地PyCharm的requests库版本是否一致(在代码中加
print(requests.__version__)),若版本差异大,将本地的requests依赖打包进Lambda部署包,确保运行环境一致。 - 排查网络代理影响:若Lambda部署在VPC内,确认是否有代理服务篡改了HTTP请求头,导致认证格式异常。
内容的提问来源于stack exchange,提问作者phenix
相关产品推荐
相关产品推荐

