防止spring-security将无效的URL重定向到登录页面
我已经设置了一个spring-boot + spring-mvc + spring-security项目。
除了无效的网址,其他所有内容现在都可以按预期工作。
如果我发出:
http://siteaddr.com/invalid/url
我希望看到我的404未找到页面,但是spring-security会首先重定向到登录页面,并且在身份验证显示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前缀,否则必须一一声明所有经过身份验证的URL。
您还可以应用其他配置来覆盖
public void configure(WebSecurity web)...
例如忽略静态资源:
web.ignoring().antMatchers("/favicon.ico", "*.css")
希望能有所帮助。
以上是 防止spring-security将无效的URL重定向到登录页面 的全部内容, 来源链接: utcz.com/qa/410777.html