启用Spring安全性时,无法加载资源(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();
有人可以帮忙吗? 提前致谢。
您可能希望确保将包含这些项目的目录设置为permitAll。
这是我的spring安全上下文文件的摘录。 在资源目录下,我有js,css和images文件夹,这些文件夹由此行授予权限。
出于某种原因,这对我不起作用:
http.authorizeRequests().antMatchers("/resources/**").permitAll();
我不得不补充一点:
http.authorizeRequests().antMatchers("/resources/**").permitAll().anyRequest().permitAll();
此外,此行必须在restrics访问的代码之后。
您也可以直接使用“/ *。js”作为特定文件或“/ resources / **”作为目录
http.authorizeRequests() .antMatchers("/", "/login", "/logout", "/error").permitAll() .antMatchers("/resources/**").permitAll() .antMatchers("/*.js").permitAll() .antMatchers("/api/**").authenticated()
添加以下内容
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**").anyRequest(); }
我有同样的问题,改变访问“permitAll”没有帮助。 我创建了一个新的http模式,我将安全性设置为“none”,然后我可以在没有身份validation的情况下下载css和js文件。
这最终对我有用。 / home(将显示登录页面)和错误消息不需要身份validation。 所有资源都是permitAll,并且/ urlurl已经过身份validation。 任何其他url(例如/ users / customers等..)都需要添加为isAuthenticated()