oauth2资源服务器不生效问题

为什么我的OAuth2资源服务器不生效呢?api/**的请求不登录也能访问.虽然security放行了,但是资源服务器为什么不拦截呢

   @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").hasRole("admin")
                .anyRequest().authenticated()
//                .and()
//                .requestMatchers()
                // /api/**请求需要OAuth鉴权
                ;
    }

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http   // 配置登录页并允许访问
                //.formLogin().permitAll()
                // 配置Basic登录
                //.and().httpBasic()
                // 配置登出页面
                .logout().logoutUrl("/logout").logoutSuccessUrl("/")
                // 配置允许访问的链接
                .and().authorizeRequests().antMatchers("/**").permitAll()
                // 其余所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                // 关闭跨域保护;
                .and().csrf().disable();


    }

引用chatgpt部分指引作答:
从你提供的代码来看,似乎没有将您的资源服务器配置注入到Spring Security中。需要在你的Security配置类中使用@EnableResourceServer注解来启用OAuth2资源服务器,并通过 configure(ResourceServerSecurityConfigurer resources) 方法来配置资源服务器的访问规则。

示例代码如下:

@Configuration
@EnableWebSecurity
@EnableResourceServer // 启用资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").hasRole("admin")
                .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 配置资源服务器拦截规则
        resources.resourceId("my-resource-id").stateless(false);
    }
}

此外还需要在你的认证服务器的配置类中,使用@EnableAuthorizationServer注解启用OAuth2认证服务器,同时使用@EnableGlobalAuthentication注解声明认证源。

示例代码如下:

@Configuration
@EnableAuthorizationServer // 启用认证服务器
@EnableGlobalAuthentication // 声明认证源
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    // 实现OAuth2认证服务器的相关配置
    // ...

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 配置OAuth2资源服务器的访问规则
        endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager)
                 .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET);
    }

    // ...
}

这样配置后,应该就可以实现OAuth2资源服务器的拦截功能了。