1. 程式人生 > 實用技巧 >Shiro簡介及SpringMVC+Shiro搭建

Shiro簡介及SpringMVC+Shiro搭建

一、 shiro簡介

  Apache Shiro是Java的一個安全框架,是一個功能強大並且容易整合的開源許可權框架,它能夠完成認證、授權、加密、會話管理等功能。認證和授權為許可權控制的核心,簡單來說,“認證”就是證明“你是誰?”Web應用程式一般做法是通過表單提交的使用者名稱及密碼達到認證目的。“授權”即是"你能做什麼?",很多系統通過資源表的形式來完成使用者能做什麼。

  Shiro可以非常容易的開發出足夠好的應用,其不僅可以用在JavaSE環境,也可以用在JavaEE環境。Shiro可以幫助我們完成:認證、授權、加密、會話管理、與Web整合、快取等。這不就是我們想要的嘛,而且Shiro的API也是非常簡單;其基本功能點如下圖所示:

  Authentication身份認證/登入,驗證使用者是不是擁有相應的身份;

  Authorization授權,即許可權驗證,驗證某個已認證的使用者是否擁有某個許可權;即判斷使用者是否能做事情,常見的如:驗證某個使用者是否擁有某個角色。或者細粒度的驗證某個使用者對某個資源是否具有某個許可權;

  Session Manager會話管理,即使用者登入後就是一次會話,在沒有退出之前,它的所有資訊都在會話中;會話可以是普通JavaSE環境的,也可以是如Web環境的;

  Cryptography加密,保護資料的安全性,如密碼加密儲存到資料庫,而不是明文儲存;

  Web Support

Web支援,可以非常容易的整合到Web環境;

  Caching:快取,比如使用者登入後,其使用者資訊、擁有的角色/許可權不必每次去查,這樣可以提高效率;

  Concurrencyshiro支援多執行緒應用的併發驗證,即如在一個執行緒中開啟另一個執行緒,能把許可權自動傳播過去;

  Testing提供測試支援;

  Run As允許一個使用者假裝為另一個使用者(如果他們允許)的身份進行訪問;

  Remember Me記住我,這個是非常常見的功能,即一次登入後,下次再來的話不用登入了。

  記住一點,Shiro不會去維護使用者、維護許可權;這些需要我們自己去設計/提供;然後通過相應的介面注入給Shiro

即可。

  接下來我們分別從外部和內部來看看Shiro的架構,對於一個好的框架,從外部來看應該具有非常簡單易於使用的API,且API契約明確;從內部來看的話,其應該有一個可擴充套件的架構,即非常容易插入使用者自定義實現,因為任何框架都不能滿足所有需求。

首先,我們從外部來看Shiro吧,即從應用程式角度的來觀察如何使用Shiro完成工作。如下圖:

  可以看到:應用程式碼直接互動的物件是Subject,也就是說Shiro的對外API核心就是Subject;其每個API的含義:

  Subject主體,代表了當前“使用者”,這個使用者不一定是一個具體的人,與當前應用互動的任何東西都是Subject,如網路爬蟲,機器人等;即一個抽象概念;所有Subject都繫結到SecurityManager,與Subject的所有互動都會委託給SecurityManager;可以把Subject認為是一個門面;SecurityManager才是實際的執行者;

  SecurityManager安全管理器;即所有與安全有關的操作都會與SecurityManager互動;且它管理著所有Subject;可以看出它是Shiro的核心,它負責與後邊介紹的其他元件進行互動,如果學習過SpringMVC,你可以把它看成DispatcherServlet前端控制器;

  Realm域,Shiro從從Realm獲取安全資料(如使用者、角色、許可權),就是說SecurityManager要驗證使用者身份,那麼它需要從Realm獲取相應的使用者進行比較以確定使用者身份是否合法;也需要從Realm得到使用者相應的角色/許可權進行驗證使用者是否能進行操作;可以把Realm看成DataSource,即安全資料來源。

  也就是說對於我們而言,最簡單的一個Shiro應用:

  1、應用程式碼通過Subject來進行認證和授權,而Subject又委託給SecurityManager;

  2、我們需要給Shiro的SecurityManager注入Realm,從而讓SecurityManager能得到合法的使用者及其許可權進行判斷。

  從以上也可以看出,Shiro不提供維護使用者/許可權,而是通過Realm讓開發人員自己注入。

  接下來我們來從Shiro內部來看下Shiro的架構,如下圖所示:


  Subject主體,可以看到主體可以是任何可以與應用互動的“使用者”;

  SecurityManager相當於SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心臟;所有具體的互動都通過SecurityManager進行控制;它管理著所有Subject、且負責進行認證和授權、及會話、快取的管理。

  Authenticator認證器,負責主體認證的,這是一個擴充套件點,如果使用者覺得Shiro預設的不好,可以自定義實現;其需要認證策略(Authentication Strategy),即什麼情況下算使用者認證通過了;

  Authrizer授權器,或者訪問控制器,用來決定主體是否有許可權進行相應的操作;即控制著使用者能訪問應用中的哪些功能;

  Realm可以有1個或多個Realm,可以認為是安全實體資料來源,即用於獲取安全實體的;可以是JDBC實現,也可以是LDAP實現,或者記憶體實現等等;由使用者提供;注意:Shiro不知道你的使用者/許可權儲存在哪及以何種格式儲存;所以我們一般在應用中都需要實現自己的Realm;

  SessionManager如果寫過Servlet就應該知道Session的概念,Session呢需要有人去管理它的生命週期,這個元件就是SessionManager;而Shiro並不僅僅可以用在Web環境,也可以用在如普通的JavaSE環境、EJB等環境;所有呢,Shiro就抽象了一個自己的Session來管理主體與應用之間互動的資料;這樣的話,比如我們在Web環境用,剛開始是一臺Web伺服器;接著又上了臺EJB伺服器;這時想把兩臺伺服器的會話資料放到一個地方,這個時候就可以實現自己的分散式會話(如把資料放到Memcached伺服器);

  SessionDAODAO大家都用過,資料訪問物件,用於會話的CRUD,比如我們想把Session儲存到資料庫,那麼可以實現自己的SessionDAO,通過如JDBC寫到資料庫;比如想把Session放到Memcached中,可以實現自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache進行快取,以提高效能;

  CacheManager快取控制器,來管理如使用者、角色、許可權等的快取的;因為這些資料基本上很少去改變,放到快取中後可以提高訪問的效能

  Cryptography密碼模組,Shiro提高了一些常見的加密元件用於如密碼加密/解密的。

二 、shiro和spring整合

我這裡用的是 SpringMvc + Mybatis + Shiro 整合,SpringMvc+ Mybatis的整合可參見:SpringMvc+Mybatis整合。Shiro實現過程中的許可權等資訊會查詢資料庫,使用的是Mybatis查詢,,實現方式參照上面連線,不再贅述,直接介紹Shiro和 Spring的整合。

  2.1 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>

  2.2 在Spring配置檔案中新增Shiro的配置

  我在springApplication.xml引入了shiro的單獨配置檔案:

<import resource="classpath:config/aC-shiro.xml"/>

  shiro的配置檔案如下:

<?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:util="http://www.springframework.org/schema/util"
   xmlns:aop="http://www.springframework.org/schema/aop" 
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
                       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                       http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
                       
default-lazy-init="true">
<description>Shiro安全配置</description>
<!-- 使用預設的WebSecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="MyShiroDbRealm" />
 <!-- cacheManager,集合spring快取工廠 -->
<!--  <property name="cacheManager" ref="shiroEhcacheManager" />-->
</bean>
<!-- 專案自定義的Realm, 所有accountService依賴的dao都需要用depends-on宣告 -->
<bean id="MyShiroDbRealm" class="com.ass.shiro.service.MyShiroDbRealm">
<!-- 
<property name="accountService" ref="accountService"/>
 -->
</bean>
<!-- Shiro Filter 
   提示: org.apache.shiro.spring.web.ShiroFilterFactoryBean 的 id 名稱必須和 web.xml 的 filter-name 一致
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- shiro的核心安全介面  -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登入時的連結 -->
<property name="loginUrl" value="/login.do" />
<!-- 登陸成功後要跳轉的連線 -->
<property name="successUrl" value="/"/>
<!-- 沒有許可權要跳轉的連結 -->
    <property name="unauthorizedUrl" value="/unauthorized.do" />
    
    <!-- shiro連線約束配置,在這裡使用自定義的 從資料庫中動態獲取資源 -->
    
    <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" /> 
      
     <!-- 上面的標籤從資料庫中取許可權資訊, 下面的標籤的許可權資訊就解除安裝xml檔案裡面,選擇一種使用即可 -->
      
     <!-- [上行的配置的覆蓋下行的配置的] 
     <property name="filterChainDefinitions">
        <value>
           /login.do = authc 
            /favicon.ico = anon
            /logout.do = logout
            /images/** = anon
            /css/** = anon
            /common/system/index.jsp = authc
            /common/ueditor/** = anon
            /common/** = anon
            /door/** = anon 
            /dwr/** = anon
            / = anon
            /core/** = anon
            /push/** = anon
       
            /** = anon
           </value>
    </property> -->
</bean>
<!-- 自定義對 shiro的連線約束,結合shiroSecurityFilter實現從資料庫中動態獲取資源,  預設的連線配置 -->
<bean id="chainDefinitionSectionMetaSource" class="com.ass.shiro.service.ChainDefinitionSectionMetaSource">
       
    <property name="filterChainDefinitions">
        <value>
        <!-- -->
            /login.do = authc 
            /favicon.ico = anon
            /logout.do = logout
            /images/** = anon
            /css/** = anon
            /common/js/jquery-1.10.2.min.js = anon
            
            
            /selectOption.do = roles[index]
            /index.jsp = perms[index:index]
            
            <!-- /** = authc  --> 
            <!-- authc必須是驗證過的,不能是"remember me",
            而user可以是"remember me",只要Subject包含principal就行。 -->
            
            <!-- 
            anon:  例子/admins/**=anon 沒有引數,表示可以匿名使用。
            authc: 例如/admins/user/**=authc表示需要認證(登入)才能使用,沒有引數
            authcBasic:例如/admins/user/**=authcBasic沒有引數表示httpBasic認證
            user:例如/admins/user/**=user沒有引數表示必須存在使用者,當登入操作時不做檢查
            
            roles:例子/admins/user/**=roles[admin],引數可以寫多個,多個時必須加上引號,並且引數之間用逗號分割,當有多個引數時,例如admins/user/**=roles["admin,guest"],每個引數通過才算通過,相當於hasAllRoles()方法。
            perms:例子/admins/user/**=perms[user:add:*],引數可以寫多個,多個時必須加上引號,並且引數之間用逗號分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當有多個引數時必須每個引數都通過才通過,想當於isPermitedAll()方法。
            rest:  例子/admins/user/**=rest[user],根據請求的方法,相當於/admins/user/**=perms[user:method] ,其中method為post,get,delete等。
ssl:例子/admins/user/**=ssl沒有引數,表示安全的url請求,協議為https
port:  例子/admins/user/**=port[8081],當請求的url的埠不是8081是跳轉到schemal://serverName:8081?queryString,其中schmal是協議http或https等,serverName是你訪問的host,8081是url配置裡port的埠,queryString
是你訪問的url裡的?後面的引數。
                        注:anon,authcBasic,auchc,user是認證過濾器,
perms,roles,ssl,rest,port是授權過濾器
             -->
        </value>
    </property>
</bean> 
<!-- 使用者授權資訊Cache, 採用EhCache
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile"  value="/WEB-INF/config/ehcache/ehcache-shiro.xml"/>
</bean> 
-->
<!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 註解 使用方式,暫時為用到。下面方式沒有驗證。
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>
 -->
</beans>

上面配置檔案中的配置:

<bean id="chainDefinitionSectionMetaSource" class="com.ass.shiro.service.ChainDefinitionSectionMetaSource">

  會在專案啟動的時候從資料庫中載入許可權資訊。

  許可權:

  一個人擁有多個角色, 一個角色包含多個許可權,人和角色1對多,角色和許可權1對多。

  對應資料庫表:

 t_user:使用者表

  t_user_role:使用者 角色中間表

  t_role:角色表

  t_role_permission:角色許可權中間表

  t_permission:許可權表

com.ass.shiro.service.ChainDefinitionSectionMetaSource

  2.3 類自動讀取資料庫中許可權資訊的實現方式

package com.ass.shiro.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ass.common.generated.dao.TPermissionMapper;
import com.ass.common.generated.model.TPermission;
import com.ass.common.generated.model.TPermissionExample;
import com.ass.common.utils.StringUtil;
/**
 * 藉助spring {@link FactoryBean} 對apache shiro的premission進行動態建立 動態的從資料庫中讀取許可權資訊
 * 
 * @author wangt
 * 
 */
@Component
public class ChainDefinitionSectionMetaSource implements
FactoryBean<Ini.Section> {
public static int i;
// shiro預設的連結定義 寫在xml上的。
private String filterChainDefinitions;
@Resource
private TPermissionMapper tPermissionMapper;
/**
 * 通過filterChainDefinitions對預設的連結過濾定義
 * 
 * @param filterChainDefinitions
 *            預設的接過濾定義
 */
public void setFilterChainDefinitions(String filterChainDefinitions) {
this.filterChainDefinitions = filterChainDefinitions;
}
@Override
public Section getObject() throws BeansException {
Ini ini = new Ini();
// 載入預設的url
ini.load(filterChainDefinitions);
System.out.println(filterChainDefinitions);
/*1載入類似以下的資訊
  /login.do = authc 
        /favicon.ico = anon
        /logout.do = logout
        /selectOption.do = roles[index]
        /index.jsp = perms[index:index]
/testDwr.jsp = perms[index:testdwr]
          
         2
         迴圈資料庫資源的url
        for (Resource resource : resourceDao.getAll()) {
if(StringUtils.isNotEmpty(resource.getValue()) && StringUtils.isNotEmpty(resource.getPermission())) {
        section.put(resource.getValue(), resource.getPermission());
        }
        }
載入資料庫t_permission 的 value 和 permission組成類似1的格式 ,
若要這樣使用, permission 需要--->  perms[permission]
 */
Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
//查詢資料庫中所有的  路徑對應需要的許可權.
TPermissionExample example = new TPermissionExample();
example.createCriteria().andPermissionIsNotNull().andValueIsNotNull().andNameIsNotNull();
List<TPermission> lst = tPermissionMapper.selectByExample(example);
for(TPermission per : lst){
//訪問某一路徑,需要對應的許可權
if(StringUtil.isNotEmpty(per.getValue())&&StringUtil.isNotEmpty(per.getPermission()))
section.put(per.getValue(), "perms["+per.getPermission()+"]");
}
//section.put("/testDwr.jsp", "perms[index:testdwr]");///testDwr.jsp = perms[index:testdwr]
/*//因為順序原因, 把/**放到最後
 *   [上面的配置覆蓋下面的配置]
 *  把("/**", "authc") 放在  ("/testDwr.jsp", "perms[index:testdwr]")  上面,
 *  /testDwr.jsp 就只需要登入, 不需要perms[index:testdwr]許可權了
 */
section.put("/**", "anon");
for(String s : section.keySet()){
System.out.println(s + "----"+ section.get(s)+"-----------section");
}
return section;
}
@Override
public Class<?> getObjectType() {
return Section.class;
}
@Override
public boolean isSingleton() {
return true;
}
}

  t_permission表的資料格式:

  2.4 Shiro 認證 授權

  在shiro的xml配置檔案有配置,認證授權的類:MyShiroDbRealm

package com.ass.shiro.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;
import org.springside.modules.utils.Encodes;
import com.ass.common.generated.model.TUser;
import com.ass.common.service.AccountService;
import com.ass.common.service.AccountServiceImpl;
import com.ass.common.utils.StringUtil;
import com.ass.shiro.dto.CurUser;
/**
 * 
 * @author wangt 2014年11月17日 下午6:06:41 
 */
@Component
public class MyShiroDbRealm extends AuthorizingRealm {
protected final Log logger = LogFactory.getLog(getClass());
@Resource
protected AccountService accountService;
/**
 * 認證回撥函式,登入時呼叫. 獲取認證資訊added by wangt
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
TUser tUser = accountService.findUserByLoginName(token.getUsername());
if (tUser != null) {
byte[] salt = Encodes.decodeHex(tUser.getSalt());
//設定同級,下級查詢許可權
boolean siblingQuery = accountService.haveSiblingQuery(tUser.getId());
boolean lowerQuery = accountService.haveLowerQuery(tUser.getId());
String queryLevel = "none";
if(siblingQuery == true && lowerQuery == true){
queryLevel = "all";
}
if(siblingQuery == true && lowerQuery == false){
queryLevel = "sibling";
}
if(siblingQuery == false && lowerQuery == true){
queryLevel = "lower";
}
SimpleAuthenticationInfo s = new SimpleAuthenticationInfo(new CurUser(tUser,queryLevel),tUser.getPassword(), ByteSource.Util.bytes(salt), getName());
return s;
} else {
return null;
}
}
/**
 * 授權查詢回撥函式, 進行鑑權但快取中無使用者的授權資訊時呼叫. 獲取授權資訊 added by wangt
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
CurUser curUser = (CurUser) principals.getPrimaryPrincipal();
//此處獲取使用者許可權的List
List<String> lst = accountService.getPermissionsByUserid(curUser.getId());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 設定使用者的許可權
info.addStringPermissions(lst);
//獲得使用者所有的角色
Set<String> roles = new HashSet<String>();
for(String str : lst){
if(StringUtil.isNotBlank(str)){
roles.add(StringUtil.split(str,":")[0]);
}
}
//設定角色       實際使用盡量用許可權。
info.addRoles(roles);
logger.info(curUser.getLoginName());
for(String s : roles){
logger.info("包含的role-->"+s);
}
for(String s : lst){
logger.info("包含的permission-->"+s);
}
return info;
}
/**
 * 設定Password校驗的Hash演算法與迭代次數.
 */
@PostConstruct
public void initCredentialsMatcher() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(AccountServiceImpl.HASH_ALGORITHM);
matcher.setHashIterations(AccountServiceImpl.HASH_INTERATIONS);
setCredentialsMatcher(matcher);
}
}

  另外說明:

  如果在jsp頁面上使用shiro的標籤,每一個標籤都會訪問一次shiro的授權函式,所以建議shiro的授權函式查詢的時候做一下快取,自己寫一個map就好.

  getPermissionsByUserid(String id) 查詢許可權的方法

  快取實現方式如下:

package com.ass.common.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;
import com.ass.base.service.BaseServiceImpl;
import com.ass.common.generated.dao.TUserMapper;
import com.ass.common.generated.model.TUser;
import com.ass.common.generated.model.TUserExample;
import com.ass.common.utils.StringUtil;
import com.ass.log.service.UserLogService;
//Spring Service Bean的標識.
@Service
public class AccountServiceImpl extends BaseServiceImpl implements AccountService{
//@Resource
//private AuthorityService authorityService;
@Resource
private TUserMapper tUserMapper;
@Resource
private CommonService commonService;
@Resource
private UserLogService userLogService;
/** 加密策略 */
public static final String HASH_ALGORITHM = "SHA-1";
/** 迭代次數 */
public static final int HASH_INTERATIONS = 1024;
/** 鹽長 */
private static final int SALT_SIZE = 8;
/**
 * 儲存新建使用者以及其角色
 * @param tUser
 * @param roles
 * @author wangt 2014年11月27日 下午5:32:19 
 */
public void saveUser(TUser tUser, String[] roles) {
// 設定安全的密碼,生成隨機的salt並經過1024次 sha-1 hash
if (StringUtil.isNotEmpty(tUser.getPassword())) {
encryptPassword(tUser);
}
//設定t_organization_code
String sql2 = "select code from t_organization where id = "+tUser.gettOrganizationId();
Map<String, Object> mp = commonService.selectOneBySql(sql2);
tUser.settOrganizationCode(StringUtil.getString(mp.get("code")));
tUserMapper.insertSelective(tUser);
//設定角色
if(null != roles){
for(String s : roles){
String sql = "insert into t_user_role set t_user_id = "+tUser.getId()+", t_role_id = "+ s;
commonService.insertBySql(sql);
}
}
//記錄日誌,暫不使用 TODO
//userLogService.addUser(tUser);
}
//更新密碼
@Override
public void updatePassword(TUser u){
if (StringUtil.isNotEmpty(u.getPassword())) {
encryptPassword(u);
}
tUserMapper.updateByPrimaryKeySelective(u);
}
/**
 * 儲存編輯後的使用者資訊以及角色
 * @param tUser
 * @param roles
 * @author wangt 2014年11月27日 下午5:32:44 
 */
public void editUser(TUser tUser, String[] roles){
if (StringUtil.isNotEmpty(tUser.getPassword())) {
encryptPassword(tUser);
}
//記錄日誌 暫不使用 TODO
//userLogService.editUser(tUser);
//設定t_organization_code
String sql2 = "select code from t_organization where id = "+tUser.gettOrganizationId();
Map<String, Object> mp = commonService.selectOneBySql(sql2);
tUser.settOrganizationCode(StringUtil.getString(mp.get("code")));
tUserMapper.updateByPrimaryKeySelective(tUser);
String sqld = "delete from t_user_role where t_user_id = "+tUser.getId();
commonService.deleteBySql(sqld);
//設定角色
if(null !=roles){
for(String s : roles){
String sql = "insert into t_user_role set t_user_id = "+tUser.getId()+", t_role_id = "+ s;
commonService.insertBySql(sql);
}
}
}
private HashMap<Long, List<String>> permissionMaps = new HashMap<Long, List<String>>();
/**
 * 獲得使用者的所有許可權 的permission
 * 傳null為當前登入人
 * @param id
 * @return List<String>
 */
public List<String> getPermissionsByUserid(Long id) {
if(id == null){
id = this.getUser().getId();
}
//防止每次訪問這個方法都要查詢資料庫
if (!permissionMaps.containsKey(id) || permissionMaps.get(id) == null ) {
this.reloadPermissionMaps(id);
}
return this.permissionMaps.get(id);
}
private void reloadPermissionMaps(Long id){
//資料庫中存 admin:add,
String sql = "select distinct p.permission permission_ from t_user u "
+ " left join t_user_role ur on ur.t_user_id=u.id "
+ " left join t_role_permission rp on rp.t_role_id=ur.t_role_id "
+ " left join t_permission p on p.id = rp.t_permission_id "
+ " where p.pid!=0 and u.id = "+id;
List<Map<String, Object>> lst = commonService.selectBySql(sql);
List<String> ls = new ArrayList<String>();
for(int i=0; i<lst.size(); i++){
ls.add(StringUtil.getString(lst.get(i).get("permission_")));
}
this.permissionMaps.put(id, ls);
}
/**
 * 獲得使用者的所有許可權 的id
 * 傳null為當前登入人
 * @param id
 * @return
 * @author wangt 2014年11月27日 下午9:44:03 
 */
public List<String> getPermissionIdsByUserid(Long id) {
if(id == null){
id = this.getUser().getId();
}
String sql = "select distinct p.id id_ from t_user u "
+ " left join t_user_role ur on ur.t_user_id=u.id "
+ " left join t_role_permission rp on rp.t_role_id=ur.t_role_id "
+ " left join t_permission p on p.id = rp.t_permission_id "
+ " where p.pid!=0 and u.id = "+id;
List<Map<String, Object>> lst = commonService.selectBySql(sql);
List<String> ls = new ArrayList<String>();
for(int i=0; i<lst.size(); i++){
ls.add(StringUtil.getString(lst.get(i).get("id_")));
}
return ls;
}
/**
 * 判斷是否是管理員
 * 傳null為當前登入人
 * @param id
 * @return
 * @author wangt 2014年11月27日 下午9:50:15 
 */
public boolean isAdmin(Long id){
if(id == null){
id = this.getUser().getId();
}
List<String> allPermissionId = this.getPermissionIdsByUserid(id);
if(allPermissionId.contains(this.getProp("admin_permission"))){
return true;
}
return false;
}
/**
 * 判斷是否有同級查詢許可權
 * 傳null為當前登入人
 * @param id
 * @return
 * @author wangt 2014年11月27日 下午9:50:15 
 */
public boolean haveSiblingQuery(Long id){
if(id == null){
id = this.getUser().getId();
}
List<String> allPermissionId = this.getPermissionIdsByUserid(id);
if(allPermissionId.contains(this.getProp("query_the_sibling"))){
return true;
}
return false;
}
/**
 * 判斷是否有查詢下級的許可權
 * 傳null為當前登入人
 * @param id
 * @return
 * @author wangt 2014年11月27日 下午9:53:12 
 */
public boolean haveLowerQuery(Long id){
if(id == null){
id = this.getUser().getId();
}
List<String> allPermissionId = this.getPermissionIdsByUserid(id);
if(allPermissionId.contains(this.getProp("query_the_lower"))){
return true;
}
return false;
}
/**
 * 通過登入名獲得使用者
 * @param LoginName
 * @return
 * @author wangt 2014年11月27日 下午5:33:06 
 */
public TUser findUserByLoginName(String LoginName) {
//適用於所用的單表操作
//比如在業務層裡面是
TUserExample example = new TUserExample();
//未刪除的使用者
example.createCriteria().andLoginNameEqualTo(LoginName).andIsdeleteEqualTo(0);
List<TUser> userList = tUserMapper.selectByExample(example);
if(userList.size() > 0){
return userList.get(0);
}else{
return null;
}
}
/**
 * 設定安全的密碼,生成隨機的salt並經過1024次 sha-1 hash
 */
private void encryptPassword(TUser TUser) {
byte[] salt = Digests.generateSalt(SALT_SIZE);
TUser.setSalt(Encodes.encodeHex(salt));
byte[] hashPassword = Digests.sha1(TUser.getPassword().getBytes(),salt, HASH_INTERATIONS);
TUser.setPassword(Encodes.encodeHex(hashPassword));
}
}

  對應的實體類和shiro的下面配置中配置的對應頁面不再講解了~

<!-- 要求登入時的連結 -->
<property name="loginUrl" value="/login.do" />
<!-- 登陸成功後要跳轉的連線 -->
<property name="successUrl" value="/"/>
<!-- 沒有許可權要跳轉的連結 -->
    <property name="unauthorizedUrl" value="/unauthorized.do" />

-------------------------------------------

參考:

  https://www.iteye.com/blog/jinnianshilongnian-2018936

  https://my.oschina.net/wangt10/blog/523015