访问受保护的Spring Boot应用程序中的静态内容

use*_*702 8 spring spring-boot

我有一个独立的Spring Boot应用程序,其中包含/ src/main/resources/templates中的模板和/ src/main/resources/static中的静态内容.我希望在身份验证之前可以访问静态内容,因此CSS也会在登录页面上加载.现在它只在验证后加载.我的安全配置如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = Logger.getLogger(SecurityConfig.class);

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        try {
            auth.inMemoryAuthentication()
            ...
        } catch (Exception e) {
            logger.error(e);
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .formLogin()
                .defaultSuccessUrl("/projects", true)
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                .permitAll()
                .and()
            .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated();
    }

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*yer 16

无论应用程序是否安全,静态内容都在classpath:/static应用程序的根目录(即/*)中提供,因此您需要匹配根目录下的特定路径.春天引导允许在默认情况下所有访问/js/**,/css/**,/images/**(见SpringBootWebSecurityConfiguration详细内容),但你可能已经转向其关闭(不能看到你的代码的其余部分).

  • `@ EnableWebSecurity`关闭默认设置. (18认同)
  • 谢谢,当我做.antMatchers("/ css/**").permitAll()`它的工作原理.我编辑了我的帖子以包含完整的安全配置.我没有看到我可以关闭默认行为的其他地方? (4认同)