我們從FilterSecurityInterceptor我們從入手看看怎樣進行授權的:
Java代碼
//這裡是攔截器攔截HTTP請求的入口
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
//這是具體的攔截調用
public void invoke(FilterInvocation fi) throws IOException, ServletException {
if ((fi.getRequest() != null) && (fi.getRequest ().getAttribute(FILTER_APPLIED) != null)
&& observeOncePerRequest) {
//在第一次進行過安全檢查之後就不會再做了
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} else {
//這是第一次收到相應的請求,需要做安全檢測,同時把標志為設置好 - FILTER_APPLIED,下次就再有請求就不會作相同的安全檢查了
if (fi.getRequest() != null) {
fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
}
//這裡是做安全檢查的地方
InterceptorStatusToken token = super.beforeInvocation(fi);
//接著向攔截器鏈執行
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse ());
} finally {
super.afterInvocation(token, null);
}
}
}
我們看看在AbstractSecurityInterceptor是怎樣對HTTP請求作安全檢測的:
Java代碼
protected InterceptorStatusToken beforeInvocation(Object object) {
Assert.notNull(object, "Object was null");
if (!getSecureObjectClass().isAssignableFrom(object.getClass())) {
throw new IllegalArgumentException("Security invocation attempted for object "
+ object.getClass().getName()
+ " but AbstractSecurityInterceptor only configured to support secure objects of type: "
+ getSecureObjectClass());
}
//這裡讀取配置FilterSecurityInterceptor的ObjectDefinitionSource屬性 ,這些屬性配置了資源的安全設置
ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource ().getAttributes(object);
if (attr == null) {
if(rejectPublicInvocations) {
throw new IllegalArgumentException(
"No public invocations are allowed via this AbstractSecurityInterceptor. "
+ "This indicates a configuration error because the "
+ "AbstractSecurityInterceptor.rejectPublicInvocations property is set to 'true'");
}
if (logger.isDebugEnabled()) {
logger.debug("Public object - authentication not attempted");
}
publishEvent(new PublicInvocationEvent(object));
return null; // no further work post-invocation
}
if (logger.isDebugEnabled()) {
logger.debug("Secure object: " + object.toString() + "; ConfigAttributes: " + attr.toString());
}
//這裡從SecurityContextHolder中去取Authentication對象,一般在登錄時 會放到SecurityContextHolder中去
if (SecurityContextHolder.getContext().getAuthentication() == null) {
credentialsNotFound(messages.getMessage ("AbstractSecurityInterceptor.authenticationNotFound",
"An Authentication object was not found in the SecurityContext"), object, attr);
}
// 如果前面沒有處理鑒權,這裡需要對鑒權進行處理
Authentication authenticated;
if (!SecurityContextHolder.getContext().getAuthentication ().isAuthenticated() || alwaysReauthenticate) {
try {//調用配置好的AuthenticationManager處理鑒權,如果鑒權不成 功,拋出異常結束處理
authenticated = this.authenticationManager.authenticate (SecurityContextHolder.getContext()
.getAuthentication());
} catch (AuthenticationException authenticationException) {
throw authenticationException;
}
// We don't authenticated.setAuthentication(true), because each provider should do that
if (logger.isDebugEnabled()) {
logger.debug("Successfully Authenticated: " + authenticated.toString());
}
//這裡把鑒權成功後得到的Authentication保存到 SecurityContextHolder中供下次使用
SecurityContextHolder.getContext().setAuthentication (authenticated);
} else {//這裡處理前面已經通過鑒權的請求,先從SecurityContextHolder 中去取得Authentication
authenticated = SecurityContextHolder.getContext ().getAuthentication();
if (logger.isDebugEnabled()) {
logger.debug("Previously Authenticated: " + authenticated.toString());
}
}
// 這是處理授權的過程
try {
//調用配置好的AccessDecisionManager來進行授權
this.accessDecisionManager.decide(authenticated, object, attr);
} catch (AccessDeniedException accessDeniedException) {
//授權不成功向外發布事件
AuthorizationFailureEvent event = new AuthorizationFailureEvent(object, attr, authenticated,
accessDeniedException);
publishEvent(event);
throw accessDeniedException;
}
if (logger.isDebugEnabled()) {
logger.debug("Authorization successful");
}
AuthorizedEvent event = new AuthorizedEvent(object, attr, authenticated);
publishEvent(event);
// 這裡構建一個RunAsManager來替代當前的Authentication對象,默認情況 下使用的是NullRunAsManager會把SecurityContextHolder中的Authentication對象清空
Authentication runAs = this.runAsManager.buildRunAs(authenticated, object, attr);
if (runAs == null) {
if (logger.isDebugEnabled()) {
logger.debug("RunAsManager did not change Authentication object");
}
// no further work post-invocation
return new InterceptorStatusToken(authenticated, false, attr, object);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Switching to RunAs Authentication: " + runAs.toString());
}
SecurityContextHolder.getContext().setAuthentication (runAs);
// revert to token.Authenticated post-invocation
return new InterceptorStatusToken(authenticated, true, attr, object);
}
}
到這裡我們假設配置AffirmativeBased作為AccessDecisionManager:
Java代碼
//這裡定義了決策機制,需要全票才能通過
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"));
}
// 這裡對棄權票進行處理,看看是全是棄權票的決定情況,默認是不通過, 由allowIfAllAbstainDecisions變量控制
checkAllowIfAllAbstainDecisions();
}
具體的投票由投票器進行,我們這裡配置了RoleVoter來進行投票:
public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config) {
int result = ACCESS_ABSTAIN;
//這裡取得資源的安全配置
Iterator iter = config.getConfigAttributes();
while (iter.hasNext()) {
ConfigAttribute attribute = (ConfigAttribute) iter.next ();
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// 這裡對資源配置的安全授權級別進行判斷,也就是匹配ROLE為前 綴的角色配置
// 遍歷每個配置屬性,如果其中一個匹配該主體持有的 GrantedAuthority,則訪問被允許。
for (int i = 0; i < authentication.getAuthorities ().length; i++) {
if (attribute.getAttribute().equals (authentication.getAuthorities()[i].getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
上面就是對整個授權過程的一個分析,從FilterSecurityInterceptor攔截Http請求入 手,然後讀取對資源的安全配置以後,把這些信息交由AccessDecisionManager來進行決 策,Spring為我們提供了若干決策器來使用,在決策器中我們可以配置投票器來完成投票 ,我們在上面具體分析了角色投票器的使用過程。