Spring Security Spring Boot :未应用安全自动配置(opaquetoken)

7vhp5slm  于 2023-04-21  发布在  Spring
关注(0)|答案(1)|浏览(216)

我正在尝试使用spring配置oauth2 opaque token授权。
根据官方Spring文档:
如果应用程序没有公开SecurityFilterChain bean,那么Sping Boot 将公开上面的默认bean。
当我尝试在没有任何授权令牌的情况下到达端点时,我能够到达它。
我需要手动添加securityfilterchain:

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
        return http.build();
    }

另一方面,文档说明:
如果应用程序没有公开OpaqueTokenIntrospector bean,那么Sping Boot 将公开上述默认bean。
然而,当我开始服务时,我得到:

***************************
APPLICATION FAILED TO START
***************************

Description:

Method filterChain in slab.tsystems.multipart.commonsupload.config.SecurityConfiguration required a bean of type 'org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector' in your configuration.

我的相关依赖项:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-oauth2-resource-server</artifactId>
    </dependency>
    <dependency>
      <groupId>com.nimbusds</groupId>
      <artifactId>oauth2-oidc-sdk</artifactId>
      <version>10.7.2</version>
      <scope>runtime</scope>
    </dependency>

为什么不应用默认行为?

wwwo4jvm

wwwo4jvm1#

正如Spring OAuth2 Resource Server文档中所解释的,您应该声明一个Bean返回introspector或创建一个CustomOpaqueTokenIntrospector
Bean

@Bean
public OpaqueTokenIntrospector introspector() {
    return new NimbusOpaqueTokenIntrospector("http://localhost:8080/oauth2/introspect", "clientid", "clientsecret");
}

或者,如果你想自定义token introspection端点响应,你可以创建一个实现OpaqueTokenIntrospector接口的CustomOpaqueTokenIntrospector。然后像这样传递给配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .authorizeHttpRequests(authorize -> authorize
                    .anyRequest().authenticated()
            )
            .oauth2ResourceServer((oAuth2ResourceServerConfigurer -> {
                oAuth2ResourceServerConfigurer
                        .opaqueToken((opaqueTokenConfigurer -> {
                             opaqueTokenConfigurer.introspector(customOpaqueTokenInstropector);
                        }));
            }));
    return http.build();
}

相关问题