Spring安全性不允许加载CSS或JS资源

Jun*_*jie 29 css java spring spring-mvc spring-security

资源在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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

任何人都可以帮忙吗?提前致谢.

Joh*_*0te 23

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

这是我的spring安全上下文文件的摘录.在资源目录下,我有js,css和images文件夹,这些文件夹由此行授予权限.

<security:intercept-url pattern="/resources/**" access="permitAll" />
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的通知,我添加了一行`http.authorizeRequests().antMatchers("/ css/**","/ js/**","/ images/**").permitAll();`into`en protected void configure(HttpSecurity http)`然后它工作,非常感谢. (17认同)

小智 19

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

http.authorizeRequests().antMatchers("/resources/**").permitAll();
Run Code Online (Sandbox Code Playgroud)

我不得不补充一点:

http.authorizeRequests().antMatchers("/resources/**").permitAll().anyRequest().permitAll();
Run Code Online (Sandbox Code Playgroud)

此外,此行必须在restrics访问的代码之后.

  • 通过这种方式,您删除了所有安全性,“。anyRequest()。permitAll()”将允许所有请求,您必须找到正确的资源路径并使用它。如果您使用Spring Security,那么通常必须对anyRequest()进行身份验证() (3认同)

小智 7

添加以下内容

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**").anyRequest();
    }
Run Code Online (Sandbox Code Playgroud)


ath*_*ena 7

我遇到了同样的问题,该permitAll()解决方案对我不起作用。我在@Override我的WebSecurityConfig班级中添加了以下方法。

@Override
public void configure(WebSecurity web) throws Exception {
    web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}
Run Code Online (Sandbox Code Playgroud)

祝你好运!


小智 5

您也可以直接使用“ /*.js”作为特定文件,或“ / resources / **”作为目录

 http.authorizeRequests()
                .antMatchers("/", "/login", "/logout", "/error").permitAll()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/*.js").permitAll()
                .antMatchers("/api/**").authenticated()
Run Code Online (Sandbox Code Playgroud)