如何在AWS API Gateway的Java 8自定义授权器中读取请求头Token
在AWS API Gateway中用Java 8实现基于请求头Token的自定义授权器
我之前也踩过类似的坑,一开始误以为要把Token映射到请求体POJO里,其实AWS Lambda授权器的输入事件已经封装了所有请求元数据,直接从里面提取请求头就行!下面是具体的实现步骤:
1. 引入必要的依赖
首先确保你的Lambda项目里包含AWS Lambda事件处理的依赖,这样才能解析API Gateway传递过来的请求事件:
<!-- Maven依赖 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-events</artifactId> <version>3.11.0</version> <!-- 可替换为最新稳定版 --> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-core</artifactId> <version>1.2.21</version> </dependency>
2. 修改Lambda Handler读取请求头Token
不需要再用自定义Token POJO接收请求体了,直接用APIGatewayProxyRequestEvent作为输入参数,从它的headers集合里提取Token:
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import java.util.Collections; import java.util.Map; public class TokenAuthorizer implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) { APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); // 从请求头获取Token,这里假设用的是标准Authorization头(格式:Bearer <token>) String authHeader = null; // 兼容不同大小写的请求头(有些客户端会把首字母大写) for (Map.Entry<String, String> header : input.getHeaders().entrySet()) { if (header.getKey().equalsIgnoreCase("authorization")) { authHeader = header.getValue(); break; } } // 校验头是否存在且格式正确 if (authHeader == null || !authHeader.startsWith("Bearer ")) { response.setStatusCode(401); response.setBody("Missing or invalid Authorization header"); return response; } // 提取纯Token(去掉Bearer前缀) String token = authHeader.substring(7).trim(); // 替换成你的实际Token验证逻辑:比如解析JWT、调用认证服务、检查过期时间等 boolean isTokenValid = validateToken(token); if (!isTokenValid) { response.setStatusCode(403); response.setBody("Invalid or expired token"); return response; } // 验证通过,生成API Gateway需要的授权策略 String policy = generateAuthPolicy("authenticated-user", "Allow", input.getRequestContext().getResourcePath()); response.setStatusCode(200); response.setBody(policy); response.setHeaders(Collections.singletonMap("Content-Type", "application/json")); return response; } // 模拟Token验证方法,替换为你的业务逻辑 private boolean validateToken(String token) { // 示例:简单判断Token非空,实际可解析JWT签名、查询数据库等 return !token.isEmpty() && token.length() > 10; } // 生成符合API Gateway要求的授权策略文档 private String generateAuthPolicy(String principalId, String effect, String resource) { return String.format( "{\"principalId\":\"%s\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"execute-api:Invoke\",\"Effect\":\"%s\",\"Resource\":\"%s\"}]}}", principalId, effect, resource ); } }
3. 配置API Gateway的自定义授权器
在API Gateway控制台创建授权器时:
- 选择Token类型的授权器
- 在Token source中填写你要读取的请求头名称(比如
Authorization),API Gateway会自动把这个头传递给Lambda - 关联你的Lambda函数,完成后可以测试授权器是否能正确提取并验证Token
内容的提问来源于stack exchange,提问作者Sumit Kukkar
相关产品推荐
相关产品推荐

