【问题标题】:Basic security not kicking in with Spring BootSpring Boot 未启动基本安全性
【发布时间】:2014-10-29 17:51:02
【问题描述】:

我正在尝试使用基本身份验证设置一个普通的 Spring Boot 环境。

基本上我唯一想要自定义的是用户、受保护的路径和自定义密码编码器。

Spring Boot 文档指出:

在不更改任何其他自动配置的情况下覆盖访问规则 功能添加一个类型为 WebConfigurerAdapter 的 @Bean @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)。

注意:我认为 WebConfigurerAdapter 应该是 WebSecurityConfigurerAdapter。

所以我尝试了以下方法:

protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers("/assets/**").permitAll()
                .antMatchers("/api/**").hasRole("USER")
                .antMatchers("/management/**").hasRole("ADMIN");
        // @formatter:on
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
        auth
            .inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin")
                    .password(passwordEncoder.encode("pwd"))
                    .roles("USER", "ADMIN")
                    .and()
                .withUser("user")
                    .password(passwordEncoder.encode("pwd"))
                    .roles("USER");
        // @formatter:on
    }
}

默认的启动安全似乎正是我想要的:

security.enable-csrf=false
security.basic.enabled=true 
security.sessions=stateless

但是,当我运行应用程序时,基本身份验证不起作用。

当我在我的 WebSecurityConfigurerAdapter 中使用 http.httpBasic() 明确配置它时:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .httpBasic()
                .and()
            .authorizeRequests()
                .antMatchers("/assets/**").permitAll()
                .antMatchers("/api/**").hasRole("USER")
                .antMatchers("/management/**").hasRole("ADMIN");
        // @formatter:on
    }

那么基本身份验证就起作用了。

所以上面的初始设置似乎没有采用默认配置。

我错过了什么吗?

【问题讨论】:

标签: spring spring-security spring-boot


【解决方案1】:

每个WebSecurityConfigurer 都有自己的过滤器链,带有自己的请求匹配器和安全规则。添加WebSecurityConfigurer(对于文档中的拼写错误感到抱歉)不会更改默认的引导自动配置过滤器链,但它也不会为其自己的过滤器链做任何魔术。你需要告诉 Spring Security 如何保护这些资源——你给了它访问规则但没有认证策略。有意义吗?

【讨论】:

  • 好的,Spring boot 中的安全性有时就像黑魔法 :-) 无论如何,如果我只想覆盖访问规则。那我应该设置不同吗?文档似乎暗示有一种方法可以使用引导默认安全设置并覆盖访问规则。 (请参阅帖子顶部的文档引用)。
  • 你所做的很好,对我来说完全有意义。我以为您在添加 httpBasic() 时说过它有效?
  • 是的,添加 httpBasic() 后它工作正常。但是默认情况下,Boot 中的安全性已经设置好了。这就是为什么在我看来它没有采用默认值......不添加 httpBasic() - 即使使用 security.basic.enabled=true - 它也不起作用。
  • 这就是为什么我认为文档中的声明“要在不更改任何其他自动配置功能的情况下覆盖访问规则,请添加带有 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 的 WebConfigurerAdapter 类型的 @Bean。”具有误导性。当我这样做并且只设置访问规则时,默认启用 http 安全不再起作用。
猜你喜欢
  • 2017-11-24
  • 2020-08-25
  • 2020-06-11
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2017-03-13
相关资源
最近更新 更多