【发布时间】:2020-04-19 22:34:47
【问题描述】:
我使用spring-boot 和Spring REST 编写了一个简单的REST API 后端。
端点将被各种第三方应用程序使用并按预期工作。
现在我想使用 spring security 和 OAUTH 2.0 来保护这些端点。
我计划使用外部OAuth 2.0 授权服务器,这样我的rest-api-backend(spring-boot 应用程序)将充当资源服务器并通过调用外部授权服务器的令牌自省端点来验证访问令牌。
每当客户端应用程序使用授权标头中的访问令牌(使用机器对机器流中的 client_credentials 授权类型从外部 authz 服务器获得的不透明承载令牌)调用我的 api-end-points 时,Spring 总是抛出以下错误:
{
"error": "access_denied",
"error_description": "Invalid token does not contain resource id (oauth2-resource)"
}
经过一番研究,通过以下方式将调用应用程序的客户端 ID 设置为资源 ID 解决了该问题:
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenService());
resources.resourceId("5ght-6117-fdc6-8787-9017-20c784a9c03a");
// super.configure(resources);
}
Spring 似乎根据资源 ID 中设置的值验证令牌自省响应中的 aud 声明。
我无法完全理解这一点,为什么 Spring 会这样做?
作为资源服务器,它应该简单地检查访问令牌是否有效,是否具有正确的范围等。
Spring 是否维护了允许客户端的白名单?
在我的例子中,有多个客户端应用程序将访问rest-api-backend,那么如何存储它们的多个客户端 ID?
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-security-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-test</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
PS:我已经检查了许多其他关于该主题的类似问题,但找不到我在这里提出的问题的答案。
【问题讨论】:
标签: java spring spring-boot spring-security oauth-2.0