经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot security 默认拦截静态资源的解决方法
来源:jb51  时间:2023/3/17 8:57:30  对本文有异议

Spring Boot security 会默认登陆之前拦截全部css, js,img等动态资源,导致我们的公开主页在登陆之前很丑陋

像这样:

网上很多解决办法都过时了比如还在使用WebSecurityConfigurerAdapte,antMatchers

  1. public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
  2. @Override
  3. public void configure(WebSecurity web) throws Exception {
  4. web
  5. .ignoring()
  6. .antMatchers("/resources/**");
  7. }
  8. }

WebSecurityConfigurerAdapter和antMatchers已经被Spring Security 6.0弃用,现最新的是使用securityFilterChain class 如下图:

  1. public class WebSecurityConfig {
  2. @Bean
  3. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  4. http
  5. .authorizeHttpRequests((requests) -> requests
  6. .requestMatchers("/", "/home").permitAll()
  7. .anyRequest().authenticated()
  8. )
  9. .formLogin((form) -> form
  10. .loginPage("/login")
  11. .permitAll()
  12. )
  13. .logout((logout) -> logout.permitAll());
  14. return http.build();
  15. }
  16. }

这里只需要添加.requestMatchers("/resources/**").permitAll()就可以允许访问resources文件下资源

注意.antMatchers 已经弃用,用.requestMatchers代替

  1. public class WebSecurityConfig {
  2. @Bean
  3. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  4. http
  5. .authorizeHttpRequests((requests) -> requests
  6. .requestMatchers("/", "/home").permitAll()
  7. //放行静态资源
  8. .requestMatchers("/resources/**").permitAll()
  9. .anyRequest().authenticated()
  10. )
  11. .formLogin((form) -> form
  12. .loginPage("/login")
  13. .permitAll()
  14. )
  15. .logout((logout) -> logout.permitAll());
  16. return http.build();
  17. }
  18. }

但是我看网上没有人解释需要注意这里“/resources/**"并不一定万能,具体链接得根据你插入css/js的路径来比如这里使用assets/**

那么你securityFilterChain class里就得是.requestMatchers("/assets/**").permitAll()

之后再运行,成功!

到此这篇关于Spring Boot security 默认拦截静态资源的文章就介绍到这了,更多相关Spring Boot security拦截静态资源内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号