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的实现中,可以看到验证过程的实现模板,在这个实现模板中,可以看到它定义了实现验证的基本过程,如以下代码所示:
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws IOException, ServletException {
-
- if (!(request instanceof HttpServletRequest)) {
- throw new ServletException("Can only process HttpServletRequest");
- }
-
- if (!(response instanceof HttpServletResponse)) {
- throw new ServletException("Can only process HttpServletResponse");
- }
-
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- HttpServletResponse httpResponse = (HttpServletResponse) response;
-
- if (requiresAuthentication(httpRequest, httpResponse)) {
- if (logger.isDebugEnabled()) {
- logger.debug("Request is to process authentication");
- }
-
- Authentication authResult;
-
- try {
- onPreAuthentication(httpRequest, httpResponse);
-
- authResult = attemptAuthentication(httpRequest);
- } catch (AuthenticationException failed) {
-
- unsuccessfulAuthentication(httpRequest, httpResponse, failed);
-
- return;
- }
-
-
- if (continueChainBeforeSuccessfulAuthentication) {
- chain.doFilter(request, response);
- }
-
- successfulAuthentication(httpRequest, httpResponse, authResult);
-
- return;
- }
-
- chain.doFilter(request, response);
- }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//检验是不是符合ServletRequest/SevletResponse的要求
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(response instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (requiresAuthentication(httpRequest, httpResponse)) {
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
//这里定义ACEGI中的Authentication对象,从而通过这个Authentication对象,来持有用户验证信息
Authentication authResult;
try {
onPreAuthentication(httpRequest, httpResponse);
//具体验证过程委托给子类完成,比如通过AuthenticationProcessingFilter来完成基于Web页面的用户验证
authResult = attemptAuthentication(httpRequest);
} catch (AuthenticationException failed) {
// Authentication failed
unsuccessfulAuthentication(httpRequest, httpResponse, failed);
return;
}
// Authentication success
if (continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
//验证工作完成后的后续工作,跳转到相应的页面,跳转的页面路径已经做好了配置
successfulAuthentication(httpRequest, httpResponse, authResult);
return;
}
chain.doFilter(request, response);
}
在看到上面的对WEB页面请求的拦截后,处理开始转到ACEGI框架中后台了,我们看到,完成验证工作的主要类在ACEGI中是AuthenticationManager。如以下代码所示:
- public final Authentication authenticate(Authentication authRequest)
- throws AuthenticationException {
- try {
-
- Authentication authResult = doAuthentication(authRequest);
- copyDetails(authRequest, authResult);
- return authResult;
- } catch (AuthenticationException e) {
- e.setAuthentication(authRequest);
- throw e;
- }
- }
-
-
-
-
-
- private void copyDetails(Authentication source, Authentication dest) {
- if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
- AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
-
- token.setDetails(source.getDetails());
- }
- }
- protected abstract Authentication doAuthentication(Authentication authentication)
- throws AuthenticationException;
public final Authentication authenticate(Authentication authRequest)
throws AuthenticationException {
try {
/*doAuthentication是一个抽象方法,由具体的AuthenticationManager实现,从而完成验证工作。传入的参数是一个Authentication对象,在这个对象中已经封装了从HttpServletRequest中得到的用户名和密码,这些信息都是在页面登录时用户输入的*/
Authentication authResult = doAuthentication(authRequest);
copyDetails(authRequest, authResult);
return authResult;
} catch (AuthenticationException e) {
e.setAuthentication(authRequest);
throw e;
}
}
/**
* Copies the authentication details from a source Authentication object to a destination one, provided the
* latter does not already have one set.
*/
private void copyDetails(Authentication source, Authentication dest) {
if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
token.setDetails(source.getDetails());
}
}
protected abstract Authentication doAuthentication(Authentication authentication)
throws AuthenticationException;
而读取用户信息的操作,我们举大家已经很熟悉的DaoAuthenticationProvider作为例子。可以看到,在配置的JdbcDaoImpl中,定义了读取用户数据的操作,如以下代码所示:
- public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled FROM users WHERE username = ?";
- public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority FROM authorities WHERE username = ?";
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
-
- List users = usersByUsernameMapping.execute(username);
-
- if (users.size() == 0) {
- throw new UsernameNotFoundException("User not found");
- }
-
- UserDetails user = (UserDetails) users.get(0);
-
- List dbAuths = authoritiesByUsernameMapping.execute(user.getUsername());
-
- addCustomAuthorities(user.getUsername(), dbAuths);
-
- if (dbAuths.size() == 0) {
- throw new UsernameNotFoundException("User has no GrantedAuthority");
- }
-
- GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray(new GrantedAuthority[dbAuths.size()]);
-
- String returnUsername = user.getUsername();
-
- if (!usernameBasedPrimaryKey) {
- returnUsername = username;
- }
-
- return new User(returnUsername, user.getPassword(), user.isEnabled(), true, true, true, arrayAuths);
- }
public static final String DEF_USERS_BY_USERNAME_QUERY = "SELECT username,password,enabled FROM users WHERE username = ?";
public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "SELECT username,authority FROM authorities WHERE username = ?";
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
//使用Spring JDBC SqlMappingQuery来完成用户信息的查询
List users = usersByUsernameMapping.execute(username);
//根据输入的用户名,没有查询到相应的用户信息
if (users.size() == 0) {
throw new UsernameNotFoundException("User not found");
}
//如果查询到一个用户列表,使用列表中的第一个作为查询得到的用户
UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[]
//使用Spring JDBC SqlMappingQuery来完成用户权限信息的查询
List dbAuths = authoritiesByUsernameMapping.execute(user.getUsername());
addCustomAuthorities(user.getUsername(), dbAuths);
if (dbAuths.size() == 0) {
throw new UsernameNotFoundException("User has no GrantedAuthority");
}
GrantedAuthority[] arrayAuths = (GrantedAuthority[]) dbAuths.toArray(new GrantedAuthority[dbAuths.size()]);
String returnUsername = user.getUsername();
if (!usernameBasedPrimaryKey) {
returnUsername = username;
}
//根据查询的用户信息和权限信息,构造User对象返回
return new User(returnUsername, user.getPassword(), user.isEnabled(), true, true, true, arrayAuths);
}
ACEGI授权器的实现
ACEGI就像一位称职的,负责安全保卫工作的警卫,在它的工作中,不但要对来访人员的身份进行检查(通过口令识别身份),还可以根据识别出来的身份,赋予其不同权限的钥匙,从而可以去打开不同的门禁,得到不同级别的服务。从这点上看,与在这个场景中的“警卫”人员承担的角色一样,ACEGI在Spring应用系统中,起到的也是类似的保卫系统安全的作用,而验证和授权,就分别对应于警卫识别来访者身份和为其赋予权限的过程。
为用户授权是由AccessDecisionManager授权器来完成的,授权的过程,在授权器的decide方法中实现,这个decide方法是AccessDecisionManger定义的一个接口方法,通过这个接口方法,可以对应好几个具体的授权器实现,对于授权器完成决策的规则实现,在这里,我们以AffirmativeBased授权器为例,看看在AffirmativeBased授权器中,实现的一票决定授权规则是怎样完成的,这个实现过程,如以下代码所示:
- public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
- throws AccessDeniedException {
-
- Iterator iter = this.getDecisionVoters().iterator();
- int deny = 0;
-
- while (iter.hasNext()) {
-
- AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
- int result = voter.vote(authentication, object, config);
-
-
- switch (result) {
- case AccessDecisionVoter.ACCESS_GRANTED:
- return;
-
- case AccessDecisionVoter.ACCESS_DENIED:
- deny++;
-
- break;
-
- default:
- break;
- }
- }
-
- if (deny > 0) {
- throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
- "Access is denied"));
- }
-
-
- checkAllowIfAllAbstainDecisions();
- }
public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config)
throws AccessDeniedException {
//取得配置投票器的迭代器,可以用来遍历所有的投票器
Iterator iter = this.getDecisionVoters().iterator();
int deny = 0;
while (iter.hasNext()) {
//取得当前投票器的投票结果
AccessDecisionVoter voter = (AccessDecisionVoter) iter.next();
int result = voter.vote(authentication, object, config);
//对投票结果进行处理,如果是遇到ACCESS_GRANT的结果,授权直接通过
//否则,累计ACCESS_DENIED的投票票数
switch (result) {
case AccessDecisionVoter.ACCESS_GRANTED:
return;
case AccessDecisionVoter.ACCESS_DENIED:
deny++;
break;
default:
break;
}
}
//如果有反对票,那么拒绝授权
if (deny > 0) {
throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
"Access is denied"));
}
// 这里对弃权票进行处理,看看是全是弃权票的决定情况,默认是不通过,这种处理情况,是由allowIfAllAbstainDecisions变量来控制的
// To get this far, every AccessDecisionVoter abstained
checkAllowIfAllAbstainDecisions();
}
可以看到,在ACEGI的框架实现中,应用的安全需求管理,主要是由过滤器、验证器、用户数据提供器、授权器、投票器,这几个基本模块的协作一起完成的。这几个基本模块的关系,刻画出了ACEGI内部架构的基本情况,也是我们基于ACEGI实现Spring安全应用,需要重点关注的地方。