Spring Security配置导致未认证用户无法加载样式的问题求助
Alright, let's get this sorted out! The root of your problem is that once you added .anyRequest().authenticated() to your Spring Security config, it’s locking down all incoming requests—including the ones for your style files at /styles/**. Since unauthenticated users aren’t logged in, Spring Security blocks those requests, which is why your page styles fail to load.
Fix Steps:
You just need to add an explicit rule to permit unauthenticated access to your style resource path before the .anyRequest().authenticated() line. Spring Security evaluates rules from top to bottom, so this new rule needs to come early in the authorizeRequests() chain to take precedence.
Updated Spring Security Configuration
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/registration").permitAll() .antMatchers("/styles/**").permitAll() // Add this line to unlock style access .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/hello") .permitAll() .and() .logout() .logoutSuccessUrl("/hello") .permitAll(); }
Why This Works:
By adding .antMatchers("/styles/**").permitAll(), you’re telling Spring Security to skip authentication checks for any request starting with /styles/. This lets unauthenticated users load your CSS files normally, while still keeping all other routes protected by authentication.
Bonus Tip:
If you have other static resources like JavaScript files or images, you can extend this rule to include those paths too:
.antMatchers("/styles/**", "/js/**", "/images/**").permitAll()
内容的提问来源于stack exchange,提问作者user13034249

