如何通过AWS API Gateway+Cognito将用户属性传递至后端Spring应用
在API Gateway中配置Cognito用户属性转发至请求头
1. 配置集成请求头映射
- 登录AWS控制台进入API Gateway,找到目标API及对应资源/方法
- 切换到「集成请求」标签,定位到「HTTP请求头」区域
- 添加自定义请求头,映射Cognito授权器返回的用户属性:
- 键:
X-User-Username,值:$context.authorizer.claims.username - 键:
X-User-Email,值:$context.authorizer.claims.email
- 键:
- 保存配置后,重新部署API到对应阶段
2. 验证Cognito Token包含目标属性
- 确认Cognito用户池已开启邮箱属性的收集与存储,且用户注册时已提交该信息
- 用JWT解析工具验证授权返回的Token,确保
username和email存在于claims中
Spring后端获取用户信息
1. 直接读取请求头
在Controller方法中通过@RequestHeader注解直接获取:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/user/profile") public UserProfile getProfile( @RequestHeader("X-User-Username") String username, @RequestHeader("X-User-Email") String email) { return new UserProfile(username, email); } static class UserProfile { private String username; private String email; public UserProfile(String username, String email) { this.username = username; this.email = email; } // Getter方法 public String getUsername() { return username; } public String getEmail() { return email; } } }
2. 全局拦截统一处理(可选)
若多个接口需用户信息,可实现拦截器将信息存入上下文:
import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserInfoInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String username = request.getHeader("X-User-Username"); String email = request.getHeader("X-User-Email"); UserContext.setCurrentUser(new UserProfile(username, email)); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { UserContext.clear(); } } // 上下文工具类 public class UserContext { private static final ThreadLocal<UserProfile> USER_HOLDER = new ThreadLocal<>(); public static void setCurrentUser(UserProfile profile) { USER_HOLDER.set(profile); } public static UserProfile getCurrentUser() { return USER_HOLDER.get(); } public static void clear() { USER_HOLDER.remove(); } }
注册拦截器:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new UserInfoInterceptor()) .addPathPatterns("/api/**"); // 指定需拦截的接口路径 } }
注意事项
- 修改API Gateway配置后必须重新部署,否则新规则不会生效
- 若Token中无
emailclaim,需检查Cognito用户池属性配置,确保邮箱为可读写状态且已被用户提交 - 生产环境中可对自定义请求头做基础校验,结合Cognito授权器保障请求合法性
内容的提问来源于stack exchange,提问作者Damian Tański
相关产品推荐
相关产品推荐

