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 资源被非授权请求阻止?

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

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

最新更新