百木园-与人分享,
就是让自己快乐。

ObjectPostProcessor使用与多种用户定义方式(9)

  

1.ObjectPostProcessor 使用

  前面介绍了 ObjectPostProcessor的基本概念。相信读者已经明白,所有的过滤器都由对应的配置类来负责创建,配置类在将过滤器创建成功之后,会调用父类的postProcess方法,该 方法最终会调用到CompositeObjectPostProcessor对象的postProcess方法,在该方法中,会遍 历 CompositeObjectPostProcessor 对象所维护的 List 集合中存储的所有 ObjectPostProcessor 对 象,并调用其postProcess方法对对象进行后置处理。默认情况下,CompositeObjectPostProcessor 对象中所维护的List集合中只有一个对象那就是AutowireBeanFactoryObjectPostProcessor调用 AutowireBeanFactoryObjectPostProcessor 的 postProcess 方法可以将对象注册到 Spring 容器 中去。

  升发者可以自定义ObjectPostProcessor对象,并添加到CompositeObjectPostProcessor所维护的List集合中,此时,当一个过滤器在创建成功之后,就会被两个对象后置处理器处理, 第一个是默认的对象后置处理器,负责将对象注册到Spring容器中;第二个是我们自定义的对象后置处理器,可以完成一些个性化配置.

  自定义ObjectPostProcessor对象比较典型的用法是动态权限配置(权限管理将在后续章节 具体介绍),为了便于大家理解,笔者这里先通过一个大家熟悉的案例来展示 ObjectPostProcessor的用法,后面在配置动态权限时,ObjectPostProcessor的使用思路是一样的。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .withObjectPostProcessor(new ObjectPostProcessor<UsernamePasswordAuthenticationFilter>(){
            @Override
            public <O extends UsernamePasswordAuthenticationFilter> O postProcess(O object) {
                object.setUsernameParameter(\"name\");
                object.setPasswordParameter(\"passwd\");
                object.setAuthenticationSuccessHandler(((request, response, authentication) -> {
                    response.getWriter().write(\"login Success\");
                }));
                return object;
            }
        })
        .and()
        .csrf().disable();
}

  在这个案例中,调用formLogin方法之后,升启了 FormLoginConfigurer的配置,FormLoginConfigurer 的作用是为了配置 UsernamePasswordAuthenticationFilter 过滤器,在 formLogin 方法执行完毕后,我们调用 withObjectPostProcessor 方法对 UsernamePasswordAuthenticationFilter 过滤器进行二次处理,修改登录参数的key,将登录用户名参数的key改为name,将登录密码参数的key改为passwd,同时配置一个登录成功的处理器。

  2.多种用户定义方式

在前面的章节中,我们定义用户主要是两种方式:

  (1)第一种方式是使用的重写configure(AuthenticationManagerBuilder)方法的方式。

  (2)第二种方式是定义多个数据源时,我们直接向Spring容器中注入了 UserDetailsService 对象。

那么这两种用户定义方式有什么区别?

  根据前面的源码分析可知,在Spring Security中存在两种类型的AuthenticationManager, 一种是全局的AuthenticationManager,另一种则是局部的AuthenticationManager局部的 AuthenticationManager,由 HttpSecurity 进行配置,而全局的 AuthenticationManager 可以不用配置,系统会默认提供一个全局的AuthenticationManager对象,也可以通过重写 configure(AuthenticationMaiiagerBuilder)方法进行全局配置。

  当进行用户身份验证时,首先会通过局部的AuthenticationManager对象进行验证,如果验证失败,则会调用其parent也就是全局的AuthenticationManager再次进行验证。

  所以开发者在定义用户时,也分为两种情况,一种是针对局部AuthenticationManager定义的用户,另一种则是针对全局AuthenticationManager定义的用户。

  为了演示方便,接下来的案例我们将采用InMemoryUserDetailsManager来构建用户对象, 读者也可以自行使用基于MyBatis或者Spring Data JPA定义的UserDetailsService实例。

先来看针对局部AuthenticationManager定义的用户:

@Override
protected void configure(HttpSecurity http) throws Exception {
    InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
    users.createUser(User.withUsername(\"buretuzi\").password(\"{noop}123\").roles(\"admin\").build());
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .permitAll()
        .and()
        .userDetailsService(users)
        .csrf().disable();
}

  在上面这段代码中,我们基于内存来管理用户,并向users中添加了一个用户,将配置好的users对象添加到HttpSecurity中,也就是配置到局部的AuthenticationManager中。

  配置完成后,启动项目。项目启动成功后,我们就可以使用buretuzi/123来登录系统了。 但是注意,当我们启动项目时,在IDEA控制台输出的日志中可以看到如下内容:

  Using generated security password: cfc7f8b5-8346-492e-b25c-90c2c4501350

  这个是系统自动生成的用户,那么我们是否可以使用系统自动生成的用户进行登录呢?答案是可以的,为什么呢?

  系统自动提供的用户对象实际上就是往Spring容器中注册了一个 InMemoryUserDetailsManager 对象. 而在前面的代码中,我们没有重写 configure(AuthenticationManagerBuilder)方法,这意味着全局的 AuthenticationManager 是通过 AuthenticationConfignration#getAuthenticationManager 方法自动生成的,在生成的过程中,会 从Spring容器中查找对应的UserDetailsService实例进行配置(具体配置在InitializeUserDetailsManagerConfigurer类中)。所以系统自动提供的用户实际上相当于是全局AuthenticationManager对应的用户。

  以上面的代码为例,当我们开始执行登录后,Spring Security首先会调用局部Authentication Manager去进行登录校验,如果登录的用户名/密码是buretuzi/123,那就直接登录成功,否则登录失败,当登录失败后,会继续调用局部AuthenticationManager的parent继续进行校验,此时如果登录的用户名/密码是user/cfc7f8b5-8346-492e-b25c-90c2c4501350,则登录成功,否则登录失败。

  这是针对局部AuthenticationManager定义的用户,我们也可以将定义的用户配置给全局 的AuthenticationManager,由于默认的全局AuthenticationManager在配置时会从Spring容器中 査找UserDetailsService实例,所以我们如果针对全局AuthenticationManager配置用户,只需要往Spring容器中注入一个UserDetailsService实例即可,代码如下:

@Bean
UserDetailsService us(){
    InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
    users.createUser(User.withUsername(\"李文若\").password(\"{noop}123\").roles(\"admin\").build());
    return users;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
    users.createUser(User.withUsername(\"buretuzi\").password(\"{noop}123\").roles(\"admin\").build());
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .permitAll()
        .and()
        .userDetailsService(users)
        .csrf().disable();
}

   配置完成后,当我们启动项目时,全局的AuthenticationManager在配置时会去Spring容器中查找UserDetailsService实例,找到的就是我们自定义的UserDetailsService实例。当我们进行登录时,系统拿着我们输入的用户名/密码,首先和buretuzi/123进行匹配,如果匹配不上的话,再去和 李文若/123进行匹配。

  当然,升发者也可以不使用Spring Security提供的默认的全局AuthenticationManager对象, 而是通过重写 Configure(AuthenticationManagerBuilder)方法来自定义全局 Authentication Manager 对象:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser(\"剑气近\").password(\"{noop}123\").roles(\"admin\");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
    users.createUser(User.withUsername(\"buretuzi\").password(\"{noop}123\").roles(\"admin\").build());
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .permitAll()
        .and()
        .userDetailsService(users)
        .csrf().disable();
}

  根据对 WebSecurityConfigurerAdapter的源码分析可知,一旦我们重写了 configure(AuthenticationManagerBuilder)方法,则全局的 AuthenticationManager 对象将不再通过 AuthenticationConfiguration#getAuthenticationManager 方法来构建,而是通过 WebSecurityConfigiuerAdapter中的localConfigureAuthenticationBuilder变量来构建,该变量也是我们重写的 configure(AuthenticationManagerBuilder)方法的参数。

  配置完成后,当我们启动项目时,全局的AuthenticationManager在构建时会直接使用 configure(AutheuticationManagerBuilder)方法的auth变量去构建,使用的用户也是我们配置给 auth变量的用户,当我们进行登录时,系统会将所输入的用户名/密码,首先和buretuzi/123进 行匹配,如果匹配不上的话,再去和 剑气近/123进行匹配。

  需要注意的是,一旦重写了 configure(AuthenticationManagerBuilder)方法,那么全局 AuthenticationManager对象中使用的用户,将以 configure(AuthenticationManagerBuilder)方法中定义的用户为准。此时,如果我们还向Spring容器中注入了另外一个UserDetailsService实例,那么该实例中定义的用户将不会生效(因为 AuthenticationConfiguration#getAuthenticationManager方法没有被调用)。

  这就是Spring Security中几种不同的用户定义方式,相信通过这几个案例,读者对于全局 AuthenticationManager和局部AuthenticationManager对象会有更加深刻的理解。


来源:https://www.cnblogs.com/liwenruo/p/16570659.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » ObjectPostProcessor使用与多种用户定义方式(9)

相关推荐

  • 暂无文章