Spring Security — 对于不存在的端点,“需要完全身份验证才能访问此资源”

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

当我尝试访问不存在的端点时,即使授权成功通过,AuthenticationEntryPoint 也会触发。如何让它进入 404 页面?

这是我的 Spring Security 配置

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http
            .cors().and()
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(customAuthenticationEntryPoint()).and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeHttpRequests()
            .requestMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated().and()
            .addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
}
java spring spring-boot spring-security
3个回答
4
投票

您需要允许所有对

/error
路径的请求。

.requestMatchers("/error").permitAll()

1
投票

彻底的答案对我来说效果很好!但为了补充,我们还可以使用调度程序,因为:

AuthorizationFilter 不仅在每个请求上运行,而且在每个调度上运行。这意味着 REQUEST 调度需要授权,还需要 FORWARD、ERROR 和 INCLUDE。

所以这也有效:

.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()

0
投票

只需将设置添加到您的 application.yml 文件中

# Logging Configuration
logging.level.org.springframework.security: DEBUG

您将在日志中看到发生了什么。就我而言,它是一个

/favicon.ico
端点

© www.soinside.com 2019 - 2024. All rights reserved.