核心概念
Subject:主體,可以看到主體可以是任何可以與應用交互的“用戶”;
SecurityManager:相當于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心臟;所有具體的交互都通過SecurityManager進行控制;它管理著所有Subject、且負責進行認證和授權、及會話、緩存的管理。
Authenticator:認證器,負責主體認證的,這是一個擴展點,如果用戶覺得Shiro默認的不好,可以自定義實現;其需要認證策略(Authentication Strategy),即什么情況下算用戶認證通過了;
Authorizer:授權器,或者訪問控制器,用來決定主體是否有權限進行相應的操作;即控制著用戶能訪問應用中的哪些功能;
Realm:可以有1個或多個Realm,可以認為是安全實體數據源,即用于獲取安全實體的;可以是JDBC實現,也可以是LDAP實現,或者內存實現等等;由用戶提供;注意:Shiro不知道你的用戶/權限存儲在哪及以何種格式存儲;所以我們一般在應用中都需要實現自己的Realm;
SessionManager:如果寫過Servlet就應該知道Session的概念,Session呢需要有人去管理它的生命周期,這個組件就是SessionManager;而Shiro并不僅僅可以用在Web環境,也可以用在如普通的JavaSE環境、EJB等環境;所有呢,Shiro就抽象了一個自己的Session來管理主體與應用之間交互的數據;可以實現分布式的會話管理;
SessionDAO:DAO大家都用過,數據訪問對象,用于會話的CRUD,比如我們想把Session保存到數據庫,那么可以實現自己的SessionDAO,通過如JDBC寫到數據庫;比如想把Session放到redis中,可以實現自己的redis SessionDAO;另外SessionDAO中可以使用Cache進行緩存,以提高性能;
CacheManager:緩存控制器,來管理如用戶、角色、權限等的緩存的;因為這些數據基本上很少去改變,放到緩存中后可以提高訪問的性能
Cryptography:密碼模塊,Shiro提高了一些常見的加密組件用于如密碼加密/解密的。
spring集成
1、導入相關依賴
<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過慮器,DelegatingFilterProx會從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過濾器
注意:名字必須要和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>
<!-- 靜態資源不需要攔截-->
/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");
//根據shiro返回的異常類路徑判斷,拋出指定異常信息
if(exceptionClassName!=null){
if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//最終會拋給異常處理器
super.addActionError("賬號不存在");
} else if (IncorrectCredentialsException.class.getName().equals(
exceptionClassName)) {
super.addActionError("用戶名/密碼錯誤");
} else {
super.addActionError("其他異常信息");//最終在異常處理器生成未知錯誤
}
}
return "login";
}
5.使用shiro注解授權
在applicationContext-shrio.xml中添加如下配置:
<!-- 開啟aop,對類代理 -->
<aop:config proxy-target-class="true"></aop:config>
<!-- 開啟shiro注解支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
在需要控制的方法上貼上注解:@RequiresPermissions("employee:view")
6.緩存管理
7.會話管理
<!--會話管理-->
在applicationContext-shrio.xml中添加如下配置:
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效時長,單位毫秒 -->
<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.通過數據庫進行認證和授權
常見注解
@RequiresAuthentication
驗證用戶是否登錄,等同于方法subject.isAuthenticated() 結果為true時。
@RequiresUser
驗證用戶是否被記憶,user有兩種含義:
一種是成功登錄的(subject.isAuthenticated() 結果為true);
另外一種是被記憶的(subject.isRemembered()結果為true)。
@RequiresGuest
驗證是否是一個guest的請求,與@RequiresUser完全相反。
換言之,RequiresUser == !RequiresGuest。
此時subject.getPrincipal() 結果為null.
@RequiresRoles
例如:
@RequiresRoles("aRoleName");
void someMethod();
如果subject中有aRoleName角色才可以訪問方法someMethod。如果沒有這個權限則會拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。
@RequiresPermissions
例如:
@RequiresPermissions({"file:read", "write:aFile.txt"} )
void someMethod();
要求subject中必須同時含有file:read和write:aFile.txt的權限才能執行方法someMethod()。否則拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。