requestMatchers("").permitAll() 不起作用

问题描述 投票:0回答:1

我正在尝试使用 Spring Boot 安全性来实现控制器身份验证。

自定义我的

filterChain
时,对于我特别允许的资源,我收到 401 未经授权。

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors()
            .and()
        .csrf().disable()
        .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeHttpRequests()
            .requestMatchers("/api/auth/**").permitAll()
            .requestMatchers("/api/test/**").permitAll()
            .requestMatchers(h2ConsolePath + "/**").permitAll()
            .anyRequest().authenticated();

        http
            .headers()
                .frameOptions().sameOrigin();

        http
            .authenticationProvider(authenticationProvider());

        http
            .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

例如,我想访问我的 h2-console,但我不希望在访问 h2-console 时发生任何身份验证。但我仍然收到状态代码 403 Forbidden 的错误消息。

即使我删除了这一行

.anyRequest().authenticated();
我也得到了同样的错误,这让我认为整个过滤器链可能没有被应用?但是当我调试它并在方法内设置断点时,程序会跳转到方法内,所以它应该被应用吗? 经过几个小时的研究,我不知道如何继续。

编辑:

我还添加了一个带有

TestController
且没有
TestResource
注释的
@PreAuthorize
,当我在 Postman 中测试它时,我收到此错误消息:

访问此资源需要完全身份验证

正如已经提到的,我感觉过滤器链没有应用,因为即使我删除

.anyRequest().authenticated
,同样的错误仍然发生,所以它对我来说没有意义。

java spring-boot spring-security
1个回答
-3
投票

我终于找到了解决办法。我回到 Java 1.8 版本并使用

antMatchers
而不是
requestMatchers

这是我的最终代码:

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors()
            .and()
        .csrf().disable()
        .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeHttpRequests()
            .antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .antMatchers(h2ConsolePath + "/**").permitAll()
            .anyRequest().authenticated();
    
    http
        .headers()
            .frameOptions().sameOrigin();
    
    http
        .authenticationProvider(authenticationProvider());

    http
        .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    
    return http.build();
  }
© www.soinside.com 2019 - 2024. All rights reserved.