当前位置: 首页 > 知识库问答 >
问题:

Spring Security在具有多个WebSecurity配置适配器实现的任何endpoint上都不起作用

乌靖
2023-03-14

我正在尝试在我的应用程序中设置Spring Security,它有3个组件:

  • REST API(在v1路径下)

我想这样设置安全性:

  • 用JWT令牌保护的REST API
  • 使用HTTP basic保护管理员
  • 无担保文件(公共资源)

我尝试在WebSecurityConfigrerAdapter的单独实现中为这3个部分配置身份验证,结果如下所示:

对于REST API:

@Configuration
@EnableWebSecurity
@Order(1)
class ApiWebSecurityConfig : WebSecurityConfigurerAdapter() {

    // FIXME: Temporary override to disable auth
    public override fun configure(http: HttpSecurity) {
        http
            .antMatcher("/v1/*")
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                    .anyRequest().permitAll()
                .and()             
                    .csrf().disable()
        }
    }

对于Spring管理员:

@Configuration
@EnableWebSecurity
@Order(2)
class AdminWebSecurityConfig(
    private val adminServerProperties: AdminServerProperties
) : WebSecurityConfigurerAdapter() {

    public override fun configure(http: HttpSecurity) {
        http.antMatcher("${adminServerProperties.contextPath}/**")
                .authorizeRequests()
                .antMatchers("${adminServerProperties.contextPath}/assets/**").permitAll()
                .antMatchers("${adminServerProperties.contextPath}/login").permitAll()
                .anyRequest()
                .authenticated()
            .and()
                .cors()
            .and()
                .formLogin()
                .loginPage("${adminServerProperties.contextPath}/login")
            .and()
                .logout()
                .logoutUrl("${adminServerProperties.contextPath}/logout")
            .and()
                .httpBasic()
            .and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers(
                     AntPathRequestMatcher("${adminServerProperties.contextPath}/instances", HttpMethod.POST.toString()),
                     AntPathRequestMatcher("${adminServerProperties.contextPath}/instances/*", HttpMethod.DELETE.toString()),
                     AntPathRequestMatcher("${adminServerProperties.contextPath}/actuator/**")
                )
    }

    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource = UrlBasedCorsConfigurationSource().apply {
        registerCorsConfiguration("/**", CorsConfiguration().apply {
            allowedOrigins = listOf("*")
            allowedMethods = listOf("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")
            allowCredentials = true
            allowedHeaders = listOf("Authorization", "Cache-Control", "Content-Type")
        })
     }
}

对于公共文件:

@Configuration
@EnableWebSecurity
@Order(3)
class DocsWebSecurityConfig : WebSecurityConfigurerAdapter() {

    public override fun configure(http: HttpSecurity) {
        http
            .requestMatchers()
            .antMatchers("/swagger-ui/**", "/docs/**", "/docs-oas3/**")
            .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
    }
}

我的主要应用程序类如下所示:

@SpringBootApplication
@EnableAdminServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableConfigurationProperties(FirebaseConfigurationProperties::class, JwtConfigurationProperties::class)
class HldpDeviceManagementApplication

fun main(args: Array<String>) {
    runApplication<HldpDeviceManagementApplication>(*args)
}

当我运行应用程序时,除了此日志输出之外,没有错误或任何安全信息:

Will not secure Ant [pattern='/v1/**']
Will not secure Ant [pattern='/admin/**']
Will not secure Or [Ant [pattern='/swagger-ui/**'], Ant [pattern='/docs/**'], Ant [pattern='/docs-oas3/**']]

有什么建议吗?为什么配置不起作用?或者我可以用另一种方式来保护应用程序,就像这样?我试着对配置做了一些更改,但似乎没有任何帮助。

共有2个答案

拓拔弘扬
2023-03-14

你没有提到什么时候它不起作用,是在你提出请求的时候,还是在应用程序启动的时候?但是,我可以帮助您进行配置,并获取解决问题所需的信息。

我将通过公开一个安全过滤链bean,尝试用配置HttpSecurity的新方法来简化您的配置。

@Configuration
public class SecurityConfiguration {

    @Bean
    @Order(0)
    public SecurityFilterChain api(HttpSecurity http) throws Exception {
         http
            .requestMatchers(requests -> requests.antMatchers("/v1/**"))
            ...
        // the rest of the configuration
        return http.build();
    }

    @Bean
    @Order(1)
    public SecurityFilterChain admin(HttpSecurity http) throws Exception {
        http
            .requestMatchers(requests -> requests.antMatchers("/admin/**"))
            ...
        // the rest of the configuration
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain docs(HttpSecurity http) throws Exception {
        http
            .requestMatchers(requests -> requests.antMatchers("/docs/**"))
            ...
        // the rest of the configuration
        return http.build();
    }

}

这是用Java编写的,但是你可以很容易地适应Kotlin,很抱歉我没有在Kotlin中提供它。有了这个简化的配置,现在您可以添加日志记录。数量组织。springframework。安全性=跟踪应用程序。属性,并通过读取日志来检查Spring Security正在做什么。

锺离旻
2023-03-14

我发现了这个问题——这是最新版本的Spring中的一个bug:https://github.com/spring-projects/spring-security/issues/10909

 类似资料:
  • 我目前想实现这样的东西: 但是在中,我们将重点关注authProvider()方法和configure() 随着最近的消息,已被弃用。经过研究,我发现了一件事: 所以我也不得不这么做 这解决了另一个问题。但现在,我发现了这个错误。 这也是我的用户服务 你们介意帮我解决这个问题!谢谢:) 我还想提一下,我还没有在网上找到答案

  • 我正在尝试为我的项目设置多个WebsecurityConfigrerAdapter,其中Spring启动执行器API使用基本身份验证进行保护,所有其他endpoint使用JWtAuthentication进行身份验证。我只是无法使它一起工作,只有较低顺序的配置可以工作。我使用Spring Boot 2.1.5。释放 带有JWT身份验证程序的安全配置1 带有用户名/密码的基本身份验证配置 我已经尝试

  • 我在向我的GsonBuilder注册多个TypeAdapter时遇到问题。似乎只有一个会开火,而第二个永远不会被考虑。如果我单独使用每一个,它似乎工作得很好。但我需要他们一起工作,而且似乎我做错了什么。此外,我目前正在使用GSON v2。2.4. Zip对象简单表单: 拉链系列: 简单形式: JsonResponseSerializer: 测试示例: 输出: 预期输出:(注意ZipSerializ

  • 我的代码中有多个WebSecurity配置适配器: 当我从ajax请求访问我的站点时,我得到:从源http://localhost:8082访问http://localhost:8080/user/authenticate的XMLHttpRequest已被CORS策略阻止:对飞行前请求的响应未通过权限改造检查:请求的资源上不存在访问控制允许源标头。 我想我的WebSecurity配置适配器中有一些

  • 我使用的Spring安全与oAuth2,但我有一个问题,我没有找到任何答案,在许多项目的例子,你有2次配置(HttpSecurity超文本传输协议)。 例如在https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/sparklr/src/main/java/org/springframe

  • 我延长了 当我打电话的时候: 什么也没发生。 刷新视图的唯一方法是再次设置适配器(请参见此答案): 我对此解决方案有两个问题: 当我再次设置适配器时,我可以看到屏幕上有一个闪烁 listview返回第一个位置。 有什么想法吗?