security的配置片段:
<http auto-config="true" lowercase-comparisons="false" access-decision-manager-ref="accessDecisionManager"> <intercept-url pattern="/images/*" filters="none"/> <intercept-url pattern="/styles/*" filters="none"/> <intercept-url pattern="/scripts/*" filters="none"/> <intercept-url pattern="/**/*.action*" access="ROLE_NORMAL"/> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" login-processing-url="/j_security_check"/> <remember-me user-service-ref="userDao" key="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/> </http> <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"> <beans:property name="decisionVoters"> <beans:list> <beans:bean class="com.wiflish.framework.util.authority.DatabaseRoleVoter"> <!--自定义的从数据库中去权限验证权限的投票器 --> <beans:property name="dynamicAuthorityManager" ref="dynamicAuthorityManager"/> </beans:bean> <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/> </beans:list> </beans:property> </beans:bean> <beans:bean id="dynamicAuthorityManager" class="com.wiflish.framework.service.authority.impl.DefaultDynamicAuthorityManagerImpl"> <beans:property name="authorityDao" ref="authorityDao"/> <!-- authorityDao为从数据库中读取权限的dao--> </beans:bean>
类com.wiflish.framework.util.authority.DatabaseRoleVoter实现org.springframework.security.AccessDecisionManager接口。
具体的验证逻辑:通过url查找该url在数据库中已配置的权限(即角色),再与已认证的authentication对象的已授权权限进行比较。就能得到该权限是否已授权。伪代码:
// 登陆的用户无权限,即未分配角色.
GrantedAuthority[] authorities = authentication.getAuthorities();
if (authorities == null || authorities.length == 0) {
return ACCESS_DENIED;
}
String url = ((FilterInvocation) object).getRequestUrl();
if (log.isDebugEnabled()) {
log.debug("当前访问的资源地址为: " + url);
}
// 检查资源是否是受保护的资源.
boolean isProtected = manager.check(url);
// 不受保护。
if (!isProtected) {
return ACCESS_GRANTED;
}
String[] grantedRoles = manager.getAuthority(url);
// 该资源未经授权。
if (CommonUtil.isEmpty(grantedRoles)) {
return ACCESS_DENIED;
}
int result = ACCESS_DENIED;
// 检查资源是否已授权.
for (GrantedAuthority auth : authorities) {
for (String roleName : grantedRoles) {
if (roleName.equals(auth.getAuthority())) {
result = ACCESS_GRANTED;
break;
}
}
}
return result;