且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

未经身份验证的用户的 Spring Security 404 页面

更新时间:2022-05-28 07:53:56

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

First of all I encourage you to use indentation when using java config to configure your security for your spring application. It helps with readability.

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

Note all top level methods on the first indentation (authRequest,formLogin,logout) all configure/update the HTTP object it self. All these elements are from the org.springframework.security.config.annotation.web.builders.HttpSecurity class.

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

The children of these classes further refine the HTTP security configuration.

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 页面.

Note .anyRequest().authenticated() is specifically stating that any request must be authenticated. So when you attempt to goto any missing url on your domain it will ask you to login rather than goto the 404 page.

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

So if you remove that statement it and then try an goto a missing url page it will redirect you to a 404 page.