java - Spring Boot和Spring Security配置关于404错误页面

标签 java spring

我对 Spring Security 和错误页面有疑问,因为当我登录应用程序时,我可以显示页面不存在的情况。

enter image description here

但是当我退出应用程序时,我的 Spring Security 默认显示登录页面。

这是我的 Spring 安全配置。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.
            jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

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

        http.
            authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/registration").permitAll()
                .antMatchers("/admin/**").hasAuthority("ADMIN")
                .antMatchers("/user_login").hasAuthority("USER").anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/login").failureUrl("/login?error=true")
                .defaultSuccessUrl("/user_login")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .and().exceptionHandling()
                .accessDeniedPage("/access-denied");


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
           .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }

}

这可以正常工作,但我不知道为什么当我退出应用程序时我会重定向到登录页面。

有什么解决办法吗?

问候!

最佳答案

//login/registration 之外的所有请求都需要对用户进行身份验证 (anyRequest(). authentiated()),当你启用 formLogin() spring 的过滤器会将所有未经身份验证的请求重定向到登录页面,即使该页面没有退出,这就是你的原因被重定向到登录并且没有收到 404 错误。

出于测试目的,您可以添加测试匹配器,而无需在 Controller 中添加实际端点,如下所示: .antMatchers("/test").permitAll() 并尝试在未经身份验证的情况下访问此端点,您将收到 404 错误页面。

附:确保 404 响应也没有被阻止(如果它是 Controller 响应,那么也启用它,因为你的 js 是允许每个人使用的)。

关于java - Spring Boot和Spring Security配置关于404错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48154709/

相关文章:

java - URL 标识符的加密算法

java - Java中的数字格式错误

html - URL 在 CSS 中。如何绑定(bind)到当前部署的任何上下文?

java - JDBC 连接错误 - 无法创建 PoolableConnectionFactory

java - 如何获取所有 NFC 类型的事件?

java - 如何处理反转字符串上的标点符号和大写?

java - 工具栏重叠内容

java - 使用 Spring 框架清空邮件

java - Spring @ContextConfiguration 中加载位置的顺序

java - 了解 OAuth2 客户端凭据流