Spring boot + Spring Security CSS静态资源拦截问题

问题描述

在使用Spring boot + Spring Security整合的时候,Spring Security对登陆进行了响应的处理操作,但是在进入登陆页的时候,出现页面报错,页面布局全部错乱的问题,查看原因发现是CSS与JS等静态文件没有被加载成功导致

问题原因

Spring Security默认会对静态文件进行拦截,这个问题在Spring MVC中也出现过,Spring MVC的解决办法是在配置文件中加入静态资源的引用配置,但是Spring boot + Spring Security整合中采用全注解方式,没有配置文件,因此需要进行如下改动:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许所有用户访问"/"和"/home"
        http.authorizeRequests()
                .antMatchers("/home").permitAll()
                //其他地址的访问均需验证权限
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")  //指定登录页是"/login"
                .defaultSuccessUrl("/list")  //登录成功后默认跳转到"list"
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/home")  //退出登录后的默认url是"/home"
                .permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/global/**");
    }
}    

Spring boot的默认静态资源放置位置是在resource/static下,可以在static下新建一个文件夹,然后在上述方法中指定跳过拦截的文件路径即可。

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值