核心概念
Subject:主體,可以看到主體可以是任何可以與應(yīng)用交互的“用戶”器钟;
SecurityManager:相當(dāng)于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher津坑;是Shiro的心臟;所有具體的交互都通過(guò)SecurityManager進(jìn)行控制傲霸;它管理著所有Subject疆瑰、且負(fù)責(zé)進(jìn)行認(rèn)證和授權(quán)眉反、及會(huì)話、緩存的管理寸五。
Authenticator:認(rèn)證器淹接,負(fù)責(zé)主體認(rèn)證的,這是一個(gè)擴(kuò)展點(diǎn)减响,如果用戶覺(jué)得Shiro默認(rèn)的不好颂鸿,可以自定義實(shí)現(xiàn)栽渴;其需要認(rèn)證策略(Authentication Strategy)墅冷,即什么情況下算用戶認(rèn)證通過(guò)了顶岸;
Authorizer:授權(quán)器宵溅,或者訪問(wèn)控制器寇损,用來(lái)決定主體是否有權(quán)限進(jìn)行相應(yīng)的操作诲祸;即控制著用戶能訪問(wèn)應(yīng)用中的哪些功能着憨;
Realm:可以有1個(gè)或多個(gè)Realm,可以認(rèn)為是安全實(shí)體數(shù)據(jù)源,即用于獲取安全實(shí)體的;可以是JDBC實(shí)現(xiàn)或链,也可以是LDAP實(shí)現(xiàn)叼耙,或者內(nèi)存實(shí)現(xiàn)等等入蛆;由用戶提供扼褪;注意:Shiro不知道你的用戶/權(quán)限存儲(chǔ)在哪及以何種格式存儲(chǔ)闹究;所以我們一般在應(yīng)用中都需要實(shí)現(xiàn)自己的Realm蹋订;
SessionManager:如果寫(xiě)過(guò)Servlet就應(yīng)該知道Session的概念丁屎,Session呢需要有人去管理它的生命周期愧怜,這個(gè)組件就是SessionManager;而Shiro并不僅僅可以用在Web環(huán)境梨撞,也可以用在如普通的JavaSE環(huán)境、EJB等環(huán)境偿曙;所有呢,Shiro就抽象了一個(gè)自己的Session來(lái)管理主體與應(yīng)用之間交互的數(shù)據(jù)傅是;可以實(shí)現(xiàn)分布式的會(huì)話管理溃斋;
SessionDAO:DAO大家都用過(guò)走哺,數(shù)據(jù)訪問(wèn)對(duì)象,用于會(huì)話的CRUD该编,比如我們想把Session保存到數(shù)據(jù)庫(kù)赃份,那么可以實(shí)現(xiàn)自己的SessionDAO炭序,通過(guò)如JDBC寫(xiě)到數(shù)據(jù)庫(kù);比如想把Session放到redis中拦耐,可以實(shí)現(xiàn)自己的redis SessionDAO火脉;另外SessionDAO中可以使用Cache進(jìn)行緩存方援,以提高性能;
CacheManager:緩存控制器镜盯,來(lái)管理如用戶犁嗅、角色功蜓、權(quán)限等的緩存的;因?yàn)檫@些數(shù)據(jù)基本上很少去改變宠蚂,放到緩存中后可以提高訪問(wèn)的性能
Cryptography:密碼模塊式撼,Shiro提高了一些常見(jiàn)的加密組件用于如密碼加密/解密的。
spring集成
1求厕、導(dǎo)入相關(guān)依賴
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.8</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>
2.在web.xml配置ShiroFilter
<!-- shiro過(guò)慮器著隆,DelegatingFilterProx會(huì)從spring容器中找shiroFilter 必須放到web.xml前面-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.添加Shiro配置文件
3.1自定義Realm
<bean id="userRealm" class="com._520it.wms.realm.UserRealm"></bean>
public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return "UserRealm";
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
if(!"admin".equals(principal)){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),getName());
return authenticationInfo;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Employee currentUser = (Employee) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
List<String> roles = new ArrayList<String>();
roles.addAll(Arrays.asList("HR MGR","ORDER MGR"));
authorizationInfo.addRoles(roles);
List<String> perms = new ArrayList<String>();
perms.addAll(Arrays.asList("employee:view","employee:delete"));
authorizationInfo.addStringPermissions(perms);
return authorizationInfo;
}
}
3.2安全管理器SecurityManager
<!-- 配置安全管理器SecurityManager -->
在applicationContext-shrio.xml中添加如下配置:
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
3.3Shiro的Web過(guò)濾器
注意:名字必須要和web.xml中配置的名字一致
在applicationContext-shrio.xml中添加如下配置:
<!-- 定義ShiroFilter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.action"/>
<property name="successUrl" value="/main.action"/>
<property name="unauthorizedUrl" value="/nopermission.jsp"/>
<property name="filterChainDefinitions">
<value>
<!-- 靜態(tài)資源不需要攔截-->
/js/**=anon
/images/**=anon
/style/**=anon
/logout.action=logout
/**=authc
</value>
</property>
</bean>
4.修改登錄方法
public String execute()throws Exception{
HttpServletRequest req = ServletActionContext.getRequest();
if(SecurityUtils.getSubject().isAuthenticated()){
return "main";
}
String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
//根據(jù)shiro返回的異常類路徑判斷,拋出指定異常信息
if(exceptionClassName!=null){
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//最終會(huì)拋給異常處理器
super.addActionError("賬號(hào)不存在");
} else if (IncorrectCredentialsException.class.getName().equals(
exceptionClassName)) {
super.addActionError("用戶名/密碼錯(cuò)誤");
} else {
super.addActionError("其他異常信息");//最終在異常處理器生成未知錯(cuò)誤
}
}
return "login";
}
5.使用shiro注解授權(quán)
在applicationContext-shrio.xml中添加如下配置:
<!-- 開(kāi)啟aop呀癣,對(duì)類代理 -->
<aop:config proxy-target-class="true"></aop:config>
<!-- 開(kāi)啟shiro注解支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
在需要控制的方法上貼上注解:@RequiresPermissions("employee:view")
6.緩存管理
7.會(huì)話管理
<!--會(huì)話管理-->
在applicationContext-shrio.xml中添加如下配置:
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效時(shí)長(zhǎng)美浦,單位毫秒 -->
<property name="globalSessionTimeout" value="60000"/>
<!-- 刪除失效的session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
<!-- 配置安全管理器SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<property name="cacheManager" ref="cacheManager"/>
<property name="sessionManager" ref="sessionManager"/>
</bean>
8.添加憑證匹配器
在applicationContext-shrio.xml中添加如下配置:
<!--自定義realm-->
<bean id="myRealm" class="com._520it.wms.realm.MyRealm">
<property name="employeeService" ref="employeeService"/>
<property name="roleService" ref="roleService"/>
<property name="permissionService" ref="permissionService"/>
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!--添加憑證匹配器(為密碼加鹽操作)-->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="1" />
</bean>
9.通過(guò)數(shù)據(jù)庫(kù)進(jìn)行認(rèn)證和授權(quán)
常見(jiàn)注解
@RequiresAuthentication
驗(yàn)證用戶是否登錄,等同于方法subject.isAuthenticated() 結(jié)果為true時(shí)项栏。
@RequiresUser
驗(yàn)證用戶是否被記憶浦辨,user有兩種含義:
一種是成功登錄的(subject.isAuthenticated() 結(jié)果為true);
另外一種是被記憶的(subject.isRemembered()結(jié)果為true)沼沈。
@RequiresGuest
驗(yàn)證是否是一個(gè)guest的請(qǐng)求流酬,與@RequiresUser完全相反。
換言之列另,RequiresUser == !RequiresGuest芽腾。
此時(shí)subject.getPrincipal() 結(jié)果為null.
@RequiresRoles
例如:
@RequiresRoles("aRoleName");
void someMethod();
如果subject中有aRoleName角色才可以訪問(wèn)方法someMethod。如果沒(méi)有這個(gè)權(quán)限則會(huì)拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)访递。
@RequiresPermissions
例如:
@RequiresPermissions({"file:read", "write:aFile.txt"} )
void someMethod();
要求subject中必須同時(shí)含有file:read和write:aFile.txt的權(quán)限才能執(zhí)行方法someMethod()晦嵌。否則拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。