成功登录后,spring重定向到具有以下内容的/error
页面
{
"timestamp" : 1586002411175,
"status" : 999,
"error" : "None",
"message" : "No message available"
}
我正在使用spring-boot 2.2.4
我的配置:
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.mvc.servlet.load-on-startup=1
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
@Configuration
public class DispatcherContextConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/favicon.ico", "/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.antMatchers("/registration/**").anonymous()
.anyRequest().authenticated()
.and()
.headers()
.defaultsDisabled()
.cacheControl()
.and()
.and()
.exceptionHandling()
.accessDeniedPage("/errors/403")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/log") // I don't want to use force redirect here
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.key("myKey");
}
// ...
}
注:
事实证明,这个错误是由对我的一个静态资源的请求失败引起的。登录页面具有项目中缺少的<script src="/resources/my-js-file.js"></script>
。我可以通过删除丢失的资源导入来解决这个问题,但这个问题可能会在未来再次出现,所以这不是一个解决方案。
我该如何防止这种情况发生
我知道我可以用.defaultSuccessUrl("/log", true)
强制重定向到起始页,但我不想这样。此外,我希望重定向到正常工作,尽管有任何未找到的资源。
在浪费了很多时间之后,我发现了发生了什么。
所以spring找不到登录页面上使用的静态资源。但它并没有返回该资源的状态404
,而是尝试呈现错误页面并将请求转发给/error
。然后spring-security拒绝此请求,因为用户未经授权。它将/error
请求保存到会话(用于成功登录后重定向(,并将用户重定向到登录页面。
当然,用户看不到这个重定向,因为在后台完成的请求返回状态302
。但主要问题是会话中保存的/error
请求。
然后用户成功登录,spring检查会话中的该属性,并重定向到/error
页面。默认情况下,spring假设您在静态资源中的某个位置有这样的页面。如果你没有这个页面,你会看到这个奇怪的错误,状态代码为999。
解决方案1
忽略安全配置中的/error
页面:
web.ignoring().antMatchers("/favicon.ico", "/resources/**", "/error");
因此,在成功登录后,此请求将不会保存到用于用户重定向的会话中。您会看到,在登录页面上,请求静态资源的状态代码将从302
更改为404
。
解决方案2
忽略弹簧引导自动配置的一部分:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
这给出了相同的结果,但从配置ErrorMvcAutoConfiguration
中禁用了一些bean,所以要小心。
我也遇到了同样的问题。我试着对每个样式表链接进行注释,看看是哪个链接导致了错误。这是我的自定义css文件。问题是,在我的css文件中,我有一个不存在的图像的url,还有另一个错误的@import语句。在评论了这些之后,一切都很好。