You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security配置导致未认证用户无法加载样式的问题求助

Solution: Allow Unauthenticated Access to Style Resources

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:52:45