防止spring-security将无效URL重定向到登录页面

我已经设置了一个spring-boot + spring-mvc + spring-security项目。

除了无效的url外,一切都按预期正常工作。

如果我发出:

http://siteaddr.com/invalid/url 

我希望看到我的404找不到页面,但是spring-security首先重定向到登录页面,并且在身份validation后显示404找不到!

我认为这不应该如何运作!

这是我的Websecurity配置:

 package com.webitalkie.webapp.config; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; import com.webitalkie.webapp.security.DatabaseUserDetailsServic; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DatabaseUserDetailsServic userDetailsService; @Autowired private ServletContext servletContext; @Override protected void configure(HttpSecurity http) throws Exception { servletContext.getFilterRegistration(AbstractSecurityWebApplicationInitializer .DEFAULT_FILTER_NAME).addMappingForUrlPatterns(EnumSet .allOf(DispatcherType.class), false, "/*"); http.csrf().disable(); http.authorizeRequests() .antMatchers("/home/", "/home", "/home/index", "/", "/favicon.ico").permitAll() .antMatchers("/contents/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/home/loginsec").failureUrl("/loginsecerror").permitAll() .and() .logout() .logoutUrl("/home/logout") .logoutSuccessUrl("/home/index") .invalidateHttpSession(true); } @Override @org.springframework.beans.factory.annotation.Autowired protected void configure( org.springframework.security.config.annotation .authentication.builders.AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder()); } public PasswordEncoder getPasswordEncoder() { return new BcryptPasswordEncoder(11); } } 

你们有什么想法吗?

要自定义特定用例,请按建议应用反转逻辑。 你可以这样做:

1)更换

 .anyRequest().authenticated() 

通过

 .anyRequest().anonymous() 

2)添加

 .antMatchers("/protected-urls/**").authenticated() 

2)中的规则必须在1)之前,因为第一场比赛适用。 除非您有受保护资源的公共URL前缀,否则您必须逐个声明所有经过身份validation的URL。

您还可以应用覆盖其他配置

 public void configure(WebSecurity web)... 

例如,忽略静态资源:

 web.ignoring().antMatchers("/favicon.ico", "*.css") 

希望有所帮助。

这是一个安全function,而不是问题。

除非明确允许,否则您的安全模型是“拒绝所有”。 如果请求路径受到保护(即与明确的permitAll路径不匹配),那么在用户进行身份validation之前,您不希望透露它不存在。 在某些情况下,404可能会泄露私人信息

.../user/jones是404? 嗯……琼斯发生了什么事

这就是设计良好的登录表单不会告诉您“用户未找到”或“无效密码”的原因,而是在所有失败案例中只说“无效凭据”以避免过多放弃。

获取无效URL以绕过安全性的唯一方法是反转您的安全模型,除非明确保护,否则将所有内容公开(“除非明确禁止,否则允许”)。 其中有一系列问题,例如每次创建新的根路径时都必须记住更新定义。