Spring Security POST请求403异常排查:Cognito认证REST API问题
问题:REST API集成AWS Cognito权限控制后POST请求返回403错误
我需要为一个包含多个端点的现有REST API应用添加权限控制。应用通过Authorization头接收客户端传来的Cognito Bearer Token,并通过application.properties中的配置地址由AWS Cognito验证令牌:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://cognito-idp.${aws.cognito.region}.amazonaws.com/${aws.user.pools.id}
已引入的依赖包
为支持该功能,已添加以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Security配置类
当前的Security配置类如下:
import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class JWTSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(authz -> authz .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers(HttpMethod.GET, "/**").permitAll() .antMatchers(HttpMethod.POST, "/**").permitAll() .anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt()); } }
当前问题
目前GET请求可以正常访问,但POST请求返回403 Forbidden错误。我已经临时开放了所有请求的权限来排查问题,推测问题出在SecurityConfiguration的configure方法中。
已做的排查处理
为解决跨域相关问题,我在应用现有自定义Filter的doFilter方法中,将Authorization添加到Access-Control-Allow-Headers头中,完整的响应头配置如下:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, X-Requested-With, remember-me");
内容的提问来源于stack exchange,提问作者Bradley D
相关产品推荐
相关产品推荐

