Spring ACEGI的根本实现原理

Spring ACEGI的基本实现原理

Spring ACEGI 作为Spring丰富生态系统中的一个非常典型的应用,安全框架Spring ACEGI的使用是非常普遍的。尽管它不属于Spring平台的范围,但由于它建立在Spring的基础上,因此可以方便地与Spring应用集成,从而 方便的为基于Spring的应用提供安全服务。 作为一个完整的Java EE安全应用解决方案,ACEGI能够为基于Spring构建的应用项目,提供全面的安全服务,它可以处理应用需要的各种典型的安全需求;例如,用户的身 份验证、用户授权,等等。ACEGI因为其优秀的实现,而被Spring开发团队推荐作为Spring应用的通用安全框架,随着Spring的广泛传播而 被广泛应用。在各种有关Spring的书籍,文档和应用项目中,都可以看到它活跃的身影。 Spring ACEGI的基本实现 关于ACEGI的基本设置,在这里就不多啰嗦了。我们关心的是ACEGI是怎样实现用户的安全需求的,比如最基本的用户验证,授权的工作原理和实现。 在ACEGI配置中,是通过AuthenticationProcessingFilter的过滤功能来启动Web页面的用户验证实现的。 AuthenticationProcessingFilter过滤器的基类是AbstractProcessingFilter,在这个 AbstractProcessingFilter的实现中,可以看到验证过程的实现模板,在这个实现模板中,可以看到它定义了实现验证的基本过程,如以 下代码所示:

Java代码

查看源代码
打印
01.public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
02.        throws IOException, ServletException {
03.        //检验是不是符合ServletRequest/SevletResponse的要求
04.        if (!(request instanceof HttpServletRequest)) {
05.            throw new ServletException("Can only process HttpServletRequest");
06.        }
07.  
08.        if (!(response instanceof HttpServletResponse)) {
09.            throw new ServletException("Can only process HttpServletResponse");
10.        }
11.  
12.        HttpServletRequest httpRequest = (HttpServletRequest) request;
13.        HttpServletResponse httpResponse = (HttpServletResponse) response;
14.  
15.        if (requiresAuthentication(httpRequest, httpResponse)) {
16.            if (logger.isDebugEnabled()) {
17.                logger.debug("Request is to process authentication");
18.            }
19.//这里定义ACEGI中的Authentication对象,从而通过这个Authentication对象,来持有用户验证信息
20.            Authentication authResult;
21.  
22.            try {
23.                onPreAuthentication(httpRequest, httpResponse);
24.//具体验证过程委托给子类完成,比如通过AuthenticationProcessingFilter来完成基于Web页面的用户验证
25.                authResult = attemptAuthentication(httpRequest);
26.            } catch (AuthenticationException failed) {
27.                // Authentication failed
28.                unsuccessfulAuthentication(httpRequest, httpResponse, failed);
29.  
30.                return;
31.            }
32.  
33.            // Authentication success
34.            if (continueChainBeforeSuccessfulAuthentication) {
35.                chain.doFilter(request, response);
36.            }
37.//验证工作完成后的后续工作,跳转到相应的页面,跳转的页面路径已经做好了配置
38.            successfulAuthentication(httpRequest, httpResponse, authResult);
39.  
40.            return;
41.        }
42.  
43.        chain.doFilter(request, response);
44.    }
在看到上面的对WEB页面请求的拦截后,处理开始转到ACEGI框架中后台了,我们看到,完成验证工作的主要类在ACEGI中是AuthenticationManager。如以下代码所示:

 

Java代码

查看源代码
打印
01.public final Authentication authenticate(Authentication authRequest)
02.        throws AuthenticationException {
03.        try {
04.              /*doAuthentication是一个抽象方法,由具体的AuthenticationManager实现,从而完成验证工作。传入的参数是一个Authentication对象,在这个对象中已经封装了从HttpServletRequest中得到的用户名和密码,这些信息都是在页面登录时用户输入的*/
05.            Authentication authResult = doAuthentication(authRequest);
06.            copyDetails(authRequest, authResult);
07.            return authResult;
08.        } catch (AuthenticationException e) {
09.            e.setAuthentication(authRequest);
10.            throw e;
11.        }
12.    }
13.  
14.    /**
15.     * Copies the authentication details from a source Authentication object to a destination one, provided the
16.     * latter does not already have one set.
17.     */
18.    private void copyDetails(Authentication source, Authentication dest) {
19.        if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
20.            AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
21.  
22.            token.setDetails(source.getDetails());
23.        }
24.    }
25.    protected abstract Authentication doAuthentication(Authentication authentication)
26.        throws AuthenticationException;
而读取用户信息的操作,我们举大家已经很熟悉的DaoAuthenticationProvider作为例子。可以看到,在配置的JdbcDaoImpl中,定义了读取用户数据的操作,如以下代码所示:

 

Java代码

查看源代码
打印
01.public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled FROM users WHERE username = ?";
02.    public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority FROM authorities WHERE username = ?";
03.    public UserDetails loadUserByUsername(String username)
04.        throws UsernameNotFoundException, DataAccessException {
05.            //使用Spring JDBC SqlMappingQuery来完成用户信息的查询
06.        List users = usersByUsernameMapping.execute(username);
07.            //根据输入的用户名,没有查询到相应的用户信息
08.        if (users.size() == 0) {
09.            throw new UsernameNotFoundException("User not found");
10.        }
11.            //如果查询到一个用户列表,使用列表中的第一个作为查询得到的用户
12.        UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[]
13.            //使用Spring JDBC SqlMappingQuery来完成用户权限信息的查询
14.        List dbAuths = authoritiesByUsernameMapping.execute(user.getUsername());
15.  
16.        addCustomAuthorities(user.getUsername(), dbAuths);
17.  
18.        if (dbAuths.size() == 0) {
19.            throw new UsernameNotFoundException("User has no GrantedAuthority");
20.        }
21.  
22.        GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray(new GrantedAuthority[dbAuths.size()]);
23.  
24.        String returnUsername = user.getUsername();
25.  
26.        if (!usernameBasedPrimaryKey) {
27.            returnUsername = username;
28.        }
29.          //根据查询的用户信息和权限信息,构造User对象返回
30.        return new User(returnUsername, user.getPassword(), user.isEnabled(), true, true, true, arrayAuths);
31.    }
ACEGI授权器的实现 ACEGI就像一位称职的,负责安全保卫工作的警卫,在它的工作中,不但要对来访人员的身份进行检查(通过口令识别身份),还可以根据识别出来的 身份,赋予其不同权限的钥匙,从而可以去打开不同的门禁,得到不同级别的服务。从这点上看,与在这个场景中的“警卫”人员承担的角色一样,ACEGI在 Spring应用系统中,起到的也是类似的保卫系统安全的作用,而验证和授权,就分别对应于警卫识别来访者身份和为其赋予权限的过程。 为用户授权是由AccessDecisionManager授权器来完成的,授权的过程,在授权器的decide方法中实现,这个decide 方法是AccessDecisionManger定义的一个接口方法,通过这个接口方法,可以对应好几个具体的授权器实现,对于授权器完成决策的规则实 现,在这里,我们以AffirmativeBased授权器为例,看看在AffirmativeBased授权器中,实现的一票决定授权规则是怎样完成 的,这个实现过程,如以下代码所示:

 

Java代码

查看源代码
打印
01.public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
02.        throws AccessDeniedException {
03.           //取得配置投票器的迭代器,可以用来遍历所有的投票器
04.        Iterator iter = this.getDecisionVoters().iterator();
05.        int deny = 0;
06.  
07.        while (iter.hasNext()) {
08.              //取得当前投票器的投票结果
09.            AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
10.            int result = voter.vote(authentication, object, config);
11.              //对投票结果进行处理,如果是遇到ACCESS_GRANT的结果,授权直接通过
12.              //否则,累计ACCESS_DENIED的投票票数
13.            switch (result) {
14.            case AccessDecisionVoter.ACCESS_GRANTED:
15.                return;
16.  
17.            case AccessDecisionVoter.ACCESS_DENIED:
18.                deny++;
19.  
20.                break;
21.  
22.            default:
23.                break;
24.            }
25.        }
26.//如果有反对票,那么拒绝授权
27.        if (deny > 0) {
28.            throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
29.                    "Access is denied"));
30.        }
31.// 这里对弃权票进行处理,看看是全是弃权票的决定情况,默认是不通过,这种处理情况,是由allowIfAllAbstainDecisions变量来控制的
32.        // To get this far, every AccessDecisionVoter abstained
33.            checkAllowIfAllAbstainDecisions();
34.    }
可以看到,在ACEGI的框架实现中,应用的安全需求管理,主要是由过滤器、验证器、用户数据提供器、授权器、投票器,这几个基本模块的协作一起完成的。 这几个基本模块的关系,刻画出了ACEGI内部架构的基本情况,也是我们基于ACEGI实现Spring安全应用,需要重点关注的地方。