首页 > 解决方案 > Spring Security 阻止非授权请求的 CSS 资源

问题描述

我正在使用 spring boot,我的 CSS 资源位于 .../src/main/resources/static 并且我有 WebSecurityConfig 类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }
}

和 MvcConfig 类:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

当我登录 css 资源被激活。当我没有登录时,我可以访问我的模板。

为什么 CSS 资源会阻止非授权请求?

对不起我的英语不好。我将非常感谢您的帮助!

标签: javaspringspring-bootspring-security

解决方案


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/control").hasRole("ADMIN")
                .antMatchers("/register", "/login_auth", "/login").permitAll()
                .antMatchers("/img/*.jpg", "/*.js", "/*.css").permitAll()...

我这样做是为了访问根静态文件夹中的文件。如果您将 em 放在文件夹下,请改为:

.antMatchers("/img/**", "/js/**", "/css/**").permitAll()

推荐阅读