Spring Security针对未经授权的请求阻止CSS资源

时间:2020-06-01 20:29:08

标签: java spring spring-boot spring-security

我正在使用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资源阻止非授权请求?

对不起,我的英语。感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

    @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()...

我这样做是为了访问静态根目录下的文件。 如果您将它们放在文件夹下,请执行以下操作:

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