Spring Security 不允许加载 CSS 或 JS 资源

新手上路,请多包涵

资源在src/main/resources/static/css或src/main/resources/static/js下,我用的是spring boot,安全等级是:

 @Configuration
@EnableWebMvcSecurity
@EnableGlobalAuthentication
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//      http.authorizeRequests().antMatchers("/", "/index", "/quizStart")
//              .permitAll().anyRequest().authenticated();
//      http.formLogin().loginPage("/login").permitAll().and().logout()
//              .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("test").password("test")
                .roles("USER");
    }
}

当我从浏览器访问“/index”时它运行良好(可以加载资源),但是,如果我取消注释类中的四行,则无法加载资源,这四行表示:

     http.authorizeRequests().antMatchers("/", "/index", "/quizStart")
            .permitAll().anyRequest().authenticated();
    http.formLogin().loginPage("/login").permitAll().and().logout()
            .permitAll();

有人可以帮忙吗?提前致谢。

原文由 Junjie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 773
2 个回答

您可能希望确保将包含这些项目的目录设置为 permitAll。

这是我的 spring 安全上下文文件的摘录。在 resources 目录下,我有 js、css 和 images 文件夹,这些文件夹是通过这一行授予权限的。

 <security:intercept-url pattern="/resources/**" access="permitAll" />

原文由 John Humphreys 发布,翻译遵循 CC BY-SA 3.0 许可协议

出于某种原因,这对我不起作用:

 http.authorizeRequests().antMatchers("/resources/**").permitAll();

我不得不添加这个:

 http.authorizeRequests().antMatchers("/resources/**").permitAll().anyRequest().permitAll();

此外,这一行必须在限制访问的代码之后。

原文由 Sande 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题