具有基本身份验证和OAuth订单问题的Spring Boot安全性

时间:2018-03-23 08:35:24

标签: java spring spring-boot spring-security

我正在尝试实施一个简单的春季启动项目。我得到了几个REST-Endpoints,我以不同的方式保护它们。一个必须由Basic Auth保护,另一个使用OAuth保护,另一个使用自定义安全实现。

REST的终点:

  • /基本/ AUTH
  • / application / secure(oauth)
  • / application / secure2(自己实施)

从教程中,我知道我已经设置了安全适配器的顺序。我的第一个目的是以十步为单位设置顺序(例如@Order(10)@Order(20)),以防我需要在其间添加其他安全过滤器。通过这样做,我调查了以下行为:

  • 如果我添加带有@Order(10)的基本身份验证过滤器和带有@Order(20)的OAuth过滤器,则只有OAuth过滤器可以正常工作。
  • 如果我使用@Order(1)@Order(2)添加基本身份验证过滤器,并使用@Order(4)添加OAuth过滤器,则两个过滤器均有效。
  • 如果我向@Order(3)添加过滤器,我会收到一条错误消息,说明订单3已在使用中且无法配置两次。

所以有一个默认的弹簧安全适配器(或其他)具有默认顺序3.我想我通过添加@EnableWebSecurity来禁用每个默认的弹簧安全行为。在我没有通过谷歌找到答案后,我的问题将是:

  • 我做得对吗?
  • 这个春季订单3的安全适配器是什么?
  • 默认安全适配器是否会阻止我的基本身份验证实现?

WebSecurityConfig:

   @Configuration
   @EnableWebSecurity
   public class WebSecurityConfig {

    @Order(10)
    @Configuration
    public class BasicAuthConfig extends WebSecurityConfigurerAdapter {
        @Value("${security.user.password}")
        private String password;
        @Value("${security.user.name}")
        private String username;

        private static final String ROLE_ADMIN = "ADMIN";

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser(username).password(password).roles(ROLE_ADMIN);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
            http.requestMatchers().antMatchers("/basic/**", "/") //
                    .and().authorizeRequests().anyRequest().authenticated() //
                    .and().httpBasic();
        }
    }

    @Order(20)
    @Configuration
    @EnableResourceServer
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class Oauth2ServerConfig extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            System.out.println("Filter called");
            // @formatter:off
            http.csrf().disable();
            http.authorizeRequests().antMatchers("/application/**").authenticated()
                    // .antMatchers(GET, "/application/secure").authenticated()
                    .anyRequest().authenticated(); 
            // @formatter:on
        }

     // offline token validator

    }

1 个答案:

答案 0 :(得分:1)

这是一个古老的问题,但是如果有人仍然想知道问题是什么,这是我的观察结果:

  • @EnableResourceServer导入ResourceServerConfiguration,其顺序为3。
  • 例如,有些方法可以允许您在order 3资源服务器配置程序之前添加两个以上的过滤器
    • 通过给它们一些负序值(尽管我不认为负值有什么特殊之处,但一个人需要考虑其他隐式web security configurers-例如,阶数为0的那个)默认情况下已启用。但这意味着在引入新功能后,框架的不同版本中的过滤器之间可能会发生冲突);
    • 通过将它们添加为资源配置器(ResourceServerConfiguration类不添加任何请求匹配器,但如果用户未配置任何内容,则强制回退到anyRequest().authenticated())。
  • 要更好地了解在已配置的请求匹配器中如何匹配路径,可以快速浏览Ant path patterns
相关问题