现在来分析授权的过程
这篇文章会接着上一篇文章,根据源码分析一下Shiro实现授权的过程,(其中Subject之前的方法不做过多解释)
注: 配置文件和代码都放在文章最下面
准备工作:
1. AuthorizedRealm: 这是一个继承了AuthorizingRealm(是AuthenticatingRealm的子类,同样是抽象类)的Realm类,用来从数据库中获取用户的身份安全信息(本例中使用静态数据来模拟从数据库中获取)并提供给Shiro来实现授权.
2.admin.jsp: 该url配置了一个roles过滤器,需要用户获取具体的角色后才能访问.
3.unAuthorized.jsp: 未通过授权后会返回的页面.
● 接上一篇文章,认证后完成登录,此时访问一个需要用户具有一定角色才能访问的url
● 我只在AuthorizedRealm中打了一个断点,为的是查看在shiro调用doGetAuthorizationInfo之前都调用了哪些方法
简要解释一下黄色框里方法的作用,
每当有一个请求来到,都会经过PathMatchingFilter类的preHandle方法来校验url
若用户没有登录,此时PathMatchingFilter类的appliedPaths属性中保存的都是配置了anon过滤器的url
若登录后,访问需要认证的页面,appliedPaths中保存的是配置loignUrl的url和所有配置authc过滤器的url
若登录后,访问需要验证权限的页面,appliedPaths中保存的是配置了角色的url
appliedPaths集合能根据不同情况储存不同的url 实现原理与OncePerRequestFilter类有关,有兴趣的可以看一看
●下面从RolesAuthorizationFilter的isAccessAllowed方法开始分析,因为在该方法中,Subject调用了有关授权的方法hasAllRoles(roles)
可以看到hasAllRoles方法有一个参数:roles,这个roles是一个Set集合,里面储存了你配置文件中对你访问的url的所有角色的配置(参考配置文件),我只配了一个
admin角色.
● 进入到DelegatingSubject类的hasAllRoles方法,
这里的this.hasPrincipals()会返回一个true,因为在用户登录后,DelegatingSubject对象的principals属性会变成用户名.
再调用this.securityManager.hasAllRoles(this.getPrincipals(), roleIdentifiers), 将用户名和角色权限传入.这里同样是委托给了securityManager来处理
● 进入到AuthorizingSecurityManager的hasAllRoles方法,
可以看到,hasAllRoles方法调用了该类的一个属性:authorizer的hasAllRoles方法. authorizer译为授权器,(认证过程中也有相同的过程,调用了authenticator(认证器)的方法).
● 进入到ModularRealmAuthorizer的hasAllRoles方法
跟认证的过程很相似,也是先断言Realm的配置(保证Realm的存在).然后迭代roleIdentifiers(也就是包含了配置文件中访问url需要的角色)集合,并且每次迭代都要
执行一次hasRole(principals, roleIdentifier)方法,把principals(用户名),和roleIdentifier(每次迭代出来的角色字符串)作为参数传入方法中,当所有角色都
迭代完成,说明realm中包含了所有的角色,授权完成,return true,可以访问.但只要有一个角色未被包含,则终止循环,return false. 本例只有一个角色,往下看
● 进入到ModularRealmAuthorizer的hasRole
从上一个方法获取的roleIdentifier会逐一和每个realm进行匹配,只要有一个realm含有该角色即可就终止循环并return true,若所有realm都不包含该角色则return
false. 这里解释一下while循环条件的含义:先看前半段,如果该realm不是Authorizer接口的一个实例,直接进行下一次循环.若是,则强转后执行realm的hasRole方法,
若含有则return true. 本例只有一个realm,接着往下走
● 进入到AuthorizingRealm的hasRole方法,
终于到了获取用户权限信息的代码实现,
● 进入AuthorizingRealm的getAuthorizationInfo方法(代码太多不方便截图,直接上代码)
protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
if(principals == null) {
return null;
} else {
AuthorizationInfo info = null;
if(log.isTraceEnabled()) {
log.trace("Retrieving AuthorizationInfo for principals [" + principals + "]");
}
Cache cache = this.getAvailableAuthorizationCache();
Object key;
if(cache != null) {
if(log.isTraceEnabled()) {
log.trace("Attempting to retrieve the AuthorizationInfo from cache.");
}
key = this.getAuthorizationCacheKey(principals);
info = (AuthorizationInfo)cache.get(key);
if(log.isTraceEnabled()) {
if(info == null) {
log.trace("No AuthorizationInfo found in cache for principals [" + principals + "]");
} else {
log.trace("AuthorizationInfo found in cache for principals [" + principals + "]");
}
}
}
if(info == null) {
info = this.doGetAuthorizationInfo(principals);
if(info != null && cache != null) {
if(log.isTraceEnabled()) {
log.trace("Caching authorization info for principals: [" + principals + "].");
}
key = this.getAuthorizationCacheKey(principals);
cache.put(key, info);
}
}
return info;
}
}
先从缓存中根据principals获取权限信息,因为是第一登录,缓存中肯定不存在,所以需要从Realm中获取权限信息
● 进入AuthorizedRealm的doGetAuthorizationInfo方法,
首先看到调用了PrincipalCollection类的一个方法:getPrimaryPrincipal. 该类包含了所有Realm的身份;该方法会获取第一个身份(获取到的身份和配置realm的顺序有关).然后doGetAuthorizationInfo
方法会根据principals从数据库中(本例为模拟数据)获取权限信息并放入一个Set集合,并设置给SimpleAuthorizationInfo对象,将其返回.
● 回到AuthorizingRealm的getAuthorizationInfo方法
将获取到的认证信息(图中的info对象)放入缓存,并将它继续返回
● 返回到AuthorizingRealm的hasRolehasRole(String roleIdentifier, AuthorizationInfo info)方法,
在此根据info中的set集合来判断是否授权成功,然后原路返回即可,授权过程完成.
--------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------
附件:
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!--1. 配置 SecurityManager!-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="realm" ref="authorizedRealm"/>
</bean>
<!--2. 配置 CacheManager. 2.1 需要加入 ehcache 的 jar 包及配置文件.-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<bean id="authorizedRealm" class="com.iamto.ld.AuthorizedRealm">
<property name="credentialsMatcher">
<bean name="hashedCredentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>
<!--4. 配置 LifecycleBeanPostProcessor. 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法.-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!--5. 启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用.-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--6. 配置 ShiroFilter.
6.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
若不一致, 则会抛出: NoSuchBeanDefinitionException. 因为 Shiro 会来 IOC 容器中查找和 <filter-name> 名字对应的 filter bean.-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/success.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!--
配置哪些页面需要受保护.
以及访问这些页面需要的权限.
1). anon 可以被匿名访问
2). authc 必须认证(即登录)后才可能访问的页面.
3). logout 登出.
4). roles 角色过滤器
-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/action.jsp = anon
/actions/action = anon
/logout = logout
/user.jsp = roles[user]
/admin.jsp = roles[admin]
# everything else requires authentication:
/** = authc
</value>
</property>
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
</bean>
</beans>
AuthorizedRealm:
public class AuthorizedRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("---------------Authorized Realm---------------");
//先将token强转为UsernamePasswordToken对象, 便于获取username.
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String userName = upToken.getUsername();
//对用户名做认证
if("unknown".equals(userName)) {
throw new UnknownAccountException("未知的用户");
} else if("monster".equals(userName)) {
throw new LockedAccountException("被锁定的用户");
}
//以下代码 模拟从数据库中取出数据
Object principal = userName;
Object hashedCredentials = "ade3f1a44c54a5a8feda6a418535ac80";
ByteSource credentialsSalt = ByteSource.Util.bytes(userName);
String realmName = this.getName();
SimpleAuthenticationInfo info =
new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
return info;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Object principal = principalCollection.getPrimaryPrincipal();
//模拟从数据库中查询数据
Set<String> roles = new HashSet<>();
if("adm".equals(principal)) {
roles.add("admin");
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
return info;
}
public static void main(String[] args) {
String hashAlgorithmName = "MD5";
Object credentials = "123456";
Object salt = "adm";
int hashIterations = 1024;
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(simpleHash);
}
}
admin.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>insert title here</title>
</head>
<body>
<h2>Admin Page!</h2>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>insert title here</title>
</head>
<body>
<h2>unauthorized!</h2>
</body>
</html>