小编给大家分享一下如何解决使用security和静态资源被拦截的问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
之前的博客中我给过如何在springboot中整合security,当时写的界面很简单,没有CSS样式,更谈不上静态资源,而现在在实际开发过程中经理让我们用security来开发,界面肯定不可能就是两个输入框,一个按钮就完事啊,当加上CSS样式的时候问题就来了。
首先是CSS样式没办法被加载,其次登录之后跳转的路径出错,随机跳转到一个CSS文件中,这让我很烦恼,查了很多资料,也问了很多前辈之后终于解决了这个问题。
下面我给出具体的代码
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private UserDetailsServiceImpl uds;
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login","/css/**","/image/*").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/login").defaultSuccessUrl("/index").permitAll().and().logout().permitAll();
}
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(uds);
}
}
上面给出了不被拦截的一些静态资源的路径 **表示可以跨文件夹
今天使用springboot整合springsecurity,出现静态资源404的状态
然后重写public void configure(WebSecurity web)
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(loadExcludePath());
}
private String[] loadExcludePath() {
return new String[]{
"/",
"/static/**",
"/templates/**",
"/img/**",
"/js/**",
"/css/**",
"/lib/**"
};
}
照道理说。这应该就可以了,然而我这里就是不能成功放行
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭跨域限制
.csrf().disable()
.authorizeRequests()
//在此处放行
.antMatchers(loadExcludePath()).permitAll()
.anyRequest().authenticated()//其他的路径都是登录后即可访问
.and()
.formLogin()
// .loginPage("/login")
// .loginProcessingUrl("/doLogin")
.successHandler(getAuthenticationSuccessHandler())
.failureHandler(getAuthenticationFailureHandler())
// .permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());
}
这里的重点是下面几句(其他的配置可以忽略)
http
//关闭跨域限制
.csrf().disable()
.authorizeRequests()
//在此处放行
.antMatchers(loadExcludePath()).permitAll()
.anyRequest().authenticated()//其他的路径都是登录后即可访问
然而尽管标红的地方也进行了放行,可是依然失败。
到目前为止,应该是已经没问题了,毕竟两个方法中都进行了放行,可是静态资源依旧404
也就是我项目中在其他位置配置了跨域的内容,如下
@Configuration
public class CORSConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders(
"access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(true)
.maxAge(3600);
super.addCorsMappings(registry);
}
}
把 CORSConfiguration 注释掉,最终问题解决~
以上是“如何解决使用security和静态资源被拦截的问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。