成功登录后,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)
开始页面,但我不想这样做。此外,我希望重定向工作正常,尽管没有找到任何资源。
发布于 2020-04-04 14:09:03
在浪费了很多时间之后,我弄明白了到底发生了什么。
因此spring无法找到登录页面上使用的静态资源。但是,它没有返回此资源的状态404
,而是尝试呈现错误页并将请求转发给/error
。然后spring安全性拒绝此请求,因为用户未被授权。它将/error
请求保存到会话(用于成功登录后重定向),并将用户重定向到登录页面。
当然,用户看不到这个重定向,因为状态302
返回在后台完成的请求。但主要问题是会话中保存的/error
请求。
然后,用户登录成功,spring检查会话中的这个属性,然后重定向到/error
页面。默认情况下是spring假设在静态资源中有这样的页面。。如果你没有这个页面,你会看到这个奇怪的错误状态代码999。
解决方案1
忽略安全配置中的/error
页面:
web.ignoring().antMatchers("/favicon.ico", "/resources/**", "/error");
因此,在成功登录后,此请求将不会保存到会话中以供用户重定向。您将看到,在登录页面上,请求到静态资源的状态代码将从302
更改为404
。
解决方案2
忽略部分spring引导自动配置:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
这给出了同样的结果,但是禁用了配置ErrorMvcAutoConfiguration
中的一些bean,所以要小心。
https://stackoverflow.com/questions/61029340
复制相似问题