【问题标题】:Spring security vs. *.css and *.js filesSpring 安全性与 *.css 和 *.js 文件
【发布时间】:2020-08-25 08:40:48
【问题描述】:

我用 *.js 和 *.css 资源建立了一个基本的 Spring Boot 项目。我激活了 Thymeleaf、Spring Web 和 Spring Security。现在:

  1. 对于 url:http://localhost:8080/css 和 js 文件正在被正确读取
  2. 对于网址:http://localhost:8080/secondcss 和 js 文件仍在正常读取中
  3. 对于 url:http://localhost:8080/second/third 应用程序不加载 css 和 js 文件

我猜这与 Spring 安全性有关。谁能指出我正确的方向,如何正确设置 SecurityConfig.java 类,以便应用程序在 url 中附加“/”之后读取文件?我知道those 解决方案,它们不起作用:( 将“/second/**”作为 antMatchers 还不够吗?


我的课:

HomeController.java

@Controller
public class HomeController {

@GetMapping("/")
public String goHome() {
    return "index";
}

@GetMapping("/second")
public String goSecond() {
    return "secondpage";
}

@GetMapping("/second/third")
public String goThird() {
    return "thirdpage";
}
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
        throws Exception {
    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    auth.inMemoryAuthentication()
            .withUser("demo")
            .password(encoder.encode("demo"))
            .roles("USER", "ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/second", "second/**").access("hasRole('USER')")
            .and()
            .formLogin();
}
}

这是项目结构:

【问题讨论】:

    标签: css spring spring-boot spring-security


    【解决方案1】:

    尝试在SecurityConfig.class中加入这个配置

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers("/**/*.{js,html,css}");
    }
    

    它将允许安全忽略 js、html 和 css 文件。

    您还忘记了配置中 second/** 之前的 /。我认为它不会影响某些事情,但您可以尝试:

    .antMatchers("/", "/second", "/second/**").access("hasRole('USER')")
    

    【讨论】:

      【解决方案2】:

      所以,经过搜索,我找到了解决方案,它比我想象的要简单。

      我在放

          <link href="css/styles.css" rel="stylesheet" type="text/css">
      

      在我的 *.html 文件中,而不是:

          <link href="/css/styles.css" rel="stylesheet" type="text/css">
      
      • href 开头有一个斜线... 每个文件的开头都应该有这个斜杠。 *.js 文件也是如此。

      希望有一天这对某人有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 2018-12-27
        相关资源
        最近更新 更多