【问题标题】:Spring Security 404 page for unauthenticated users未经身份验证的用户的 Spring Security 404 页面
【发布时间】:2017-08-05 11:07:25
【问题描述】:

我正在使用 Spring Boot 和 Thymeleaf。我在src/main/resources/templates/error/404.html 中定义了一个自定义的 404 模板页面

当用户登录时,这可以正常工作。

但是,当他们注销时,他们不会得到任何类型的 404 页面,他们只会被重定向回 /login

我认为我的安全配置需要更改,但不确定是什么。

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

  http.authorizeRequests()
      .antMatchers("/","/register*","/resetPassword","/forgotPassword","/login","/404").permitAll()
      .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
      .authenticated().and().formLogin().loginPage("/login").failureUrl("/login?error")
      .defaultSuccessUrl("/dashboard").successHandler(successHandler)
      .usernameParameter("email").passwordParameter("password")
      .and().logout()
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").and()
      .exceptionHandling().accessDeniedPage("/access-denied");
}

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

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    首先,我鼓励您在使用 java config 为 Spring 应用程序配置安全性时使用缩进。它有助于提高可读性。

    注意第一个缩进的所有顶级方法(authRequest、formLogin、logout)都配置/更新它自己的 HTTP 对象。所有这些元素都来自org.springframework.security.config.annotation.web.builders.HttpSecurity 类。

    这些类的子类进一步完善了 HTTP 安全配置。

    http
    .authorizeRequests()
      .antMatchers("/","/register*","/resetPassword","/forgotPassword","/login","/404")
      .permitAll()
      .antMatchers("/admin/**").hasAuthority("ADMIN")
      .anyRequest().authenticated() // <--------
      .and()
    .formLogin()
      .loginPage("/login")
      .failureUrl("/login?error")
      .defaultSuccessUrl("/dashboard")
      .usernameParameter("email").passwordParameter("password")
      .and()
    .logout()
      .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
      .logoutSuccessUrl("/login?logout")
      .and()
    .exceptionHandling()
      .accessDeniedPage("/access-denied");
    

    注意.anyRequest().authenticated() 明确指出任何请求都必须经过身份验证。因此,当您尝试转到您的域上任何丢失的 url 时,它会要求您登录而不是转到 404 页面。

    因此,如果您删除该语句,然后尝试转到缺少的 url 页面,它会将您重定向到 404 页面。

    【讨论】:

    • 在评论“.anyRequest().authenticated()”后验证无效,任何人都可以访问只分配给ADMIN的页面。
    【解决方案2】:

    如果你删除 .anyRequest().Authenticated() 那么你可以在没有认证的情况下登录。

    因此,请勿尝试删除。例如,如果您访问地址“http://localhost:8080/user”,那么您将被带到授权页面。如果您尝试进入页面“http://localhost:8080/user/”,那么您将被带到用户页面。请注意,链接的不同之处仅在于末尾的正斜杠。当然,如果您在这种情况下删除“.anyRequest().Authenticated()”,则需要向 antMatchers 添加更多参数,例如“/user”和“/user/”

    因此,要小心谨慎。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-09
      • 2016-08-15
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2017-05-10
      • 2012-03-22
      • 2017-04-07
      相关资源
      最近更新 更多