Skip to main content
 首页 » 编程设计

spring-boot中Spring Boot 2 Security 登录时下载字体文件

2025年12月25日18zdz8207

我已经使用登录表单设置了一个 Spring Boot 2 应用程序,但是,当您登录时,它不会像预期的那样重定向到 /admin ,而是下载样式表引用的字体文件通过@import。

这是我的安全设置;

@Configuration 
@EnableWebSecurity() 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
 
    @Autowired 
    UserService userService; 
 
    @Bean 
    public PasswordEncoder passwordEncoder() { 
        return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 
    } 
 
    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); 
    } 
 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
        http.csrf().disable(); 
 
        // These pages don't require the user to be logged in 
        http.authorizeRequests() 
                .antMatchers("/", "/login", "/logout", "/report/**").permitAll() 
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() 
                .anyRequest().authenticated(); 
 
        // When the user has logged in as XX. 
        // But access a page that requires role YY, 
        // AccessDeniedException will be thrown. 
        http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403"); 
 
        // Config for Login Form 
        http.authorizeRequests().and().formLogin()// 
                // Submit URL of login page. 
                .loginProcessingUrl("/j_spring_security_check") // Submit URL 
                .loginPage("/login")// 
                .defaultSuccessUrl("/admin")// 
                .failureUrl("/login?error=true")// 
                .usernameParameter("username")// 
                .passwordParameter("password") 
                // Config for Logout Page 
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout=true"); 
    } 
} 

我哪里出错了?据我所知,我允许访问存储在 static 文件夹中的 Spring 资源。

请您参考如下方法:

我弄清楚了这一点,我阅读了允许访问资源的代码,并注意到它说“atCommonLocations”,并且猜测这会添加对 css、js、img、图像等文件夹的访问权限。我的文件夹中有字体标记为 webfonts,因此我更新了我的安全配置;

http.authorizeRequests() 
                .antMatchers("/", "/login", "/logout", "/report/**", "/webfonts/**").permitAll() 
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() 
                .anyRequest().authenticated();