SpringScurity中css等静态资源访问

经常有小伙伴说自己配置了SpringScurity后,访问静态资源时出现各种各样的问题,比如访问html时前端页面出现了MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff)的报错,报错码是302,http中302的表示是暂时性转移(Temporarily Moved ),意思是访问的内容被重定向了,这种情况十有八九都是被后端的过滤器给拦截了,于是在这里统一对SpringScurity配置静态资源讲解下,也算是给自己做做笔记。

首先要在项目中设置静态资源的目录,比如我的html放在templates文件夹下而css和js放在了static文件夹:

相应的就要设置静态资源的路径为:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").
                addResourceLocations("classpath:/templates/","classpath:/static/");
    }
}

上面的设置只是表示你在项目中访问静态资源时可以不用带templates和static的路径了,接下来还要配置SpringScurity的静态请求不拦截,两种方法:

方法一:

@Configuration
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 加密
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()                    //  定义当需要用户登录时候,转到的登录页面。
                .loginPage("/login.html")           // 设置登录页面
                .loginProcessingUrl("/user/login")  // 自定义的登录接口
                .and()
                .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login.html","/css/**").permitAll()     // 设置所有人都可以访问登录页面以及css资源
                .anyRequest()               // 任何请求,登录后可以访问
                .authenticated()
                .and()
                .csrf().disable();          // 关闭csrf防护
    }
}

 方法二:

@Configuration
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter {
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 加密
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()                    //  定义当需要用户登录时候,转到的登录页面。
                .loginPage("/login.html")           // 设置登录页面
                .loginProcessingUrl("/user/login")  // 自定义的登录接口
                .and()
                .authorizeRequests()        // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/login.html").permitAll()     // 设置所有人都可以访问登录页面
                .anyRequest()               // 任何请求,登录后可以访问
                .authenticated()
                .and()
                .csrf().disable();          // 关闭csrf防护
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置静态资源不要拦截
        web.ignoring().antMatchers("/css/**");
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值