我们将AWS Cognito用于Oauth2。我们的用户界面基于Angular构建。用户登录后,我发起对Cognito的调用以获取授权令牌。我正在将PKCE中的授权代码授予用于从Cognito获得令牌。从Cognito获得帮助之后,我给自己的Spring Boot REST服务打电话。从Angular调用Spring Boot服务时,我将授权标头中的令牌作为“承载者”令牌发送。
这是我的ResourceServerConfiguration.java:
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "resource-server-rest-api";
private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('openid')";
private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('openid')";
private static final String SECURED_PATTERN = "/**";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers(SECURED_PATTERN).and().authorizeRequests()
.antMatchers(HttpMethod.POST, SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
.anyRequest().access(SECURED_READ_SCOPE);
}
}
调用REST服务时,我的Angular UI会收到HTTP响应401,并显示以下错误消息:
DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter - Authentication request failed: error="invalid_token", error_description="Invalid access token: eyJraWQiOiIy.......
在此感谢您为解决此问题提供的任何帮助。
答案 0 :(得分:1)
以下更改对我有用
删除@EnableResourceServer
在下面添加到您的spring安全配置中
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS,"**").permitAll()
.anyRequest()
.authenticated()
.and().oauth2ResourceServer().jwt();
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://cognito-idp.us-east-1.amazonaws.com/{{userpoolid}}
com:
ixortalk:
security:
jwt:
aws:
userPoolId: {{userpoolid}}
region: "us-east-1"