Spring Security with Spring Boot:使用过滤器时,允许未经身份验证的用户访问特定端点

AA_*_*_PV 6 authentication rest spring spring-security spring-boot

我在这里努力应对Spring Security的基础知识。

我希望达到的目标

我的系统仅用于REST API处理,有一个登录端点POST /user/sign_in和几个打开的端点-GET /prompt/, /prompt/{id}, /story/, /story/{id},其余所有内容仅用于经过身份验证的用户。


我有一个自定义的身份验证过滤器,该过滤器已放在之前BasicAuthenticationFilter。我在这里共享我的WebSecurityConfigurerAdapter代码

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DemoAuthenticationProvider demoAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/version", "/story", "/prompt").permitAll()
                .antMatchers(HttpMethod.POST, "/user/sign_in").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(demoAuthenticationProvider);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于开放端点的匿名用户,我在过滤器中返回了一个空的身份验证令牌,并且

403访问被拒绝

当我提到允许所有身份并且不仅仅针对那些端点进行身份验证时,为什么需要身份验证令牌?我该如何正确实施呢?

AA_*_*_PV 5

我的错!

spring-boot 的端点 = 控制器的请求映射 + 方法的请求映射。我提到的 GET 映射在/. 更改为

.antMatchers(HttpMethod.GET, "/version/", "/story/", "/prompt/").permitAll()
                .antMatchers(HttpMethod.POST, "/user/sign_in/").permitAll()
Run Code Online (Sandbox Code Playgroud)

事情正在滚动。