shiro

本文主要是一下兩篇文章的綜合,感覺都不錯,拿來報訊學習一下

http://blog.csdn.net/qq_33556185/article/details/51579680

http://blog.csdn.net/u013142781/article/details/50629708

詳解登錄認證及授權--Shiro系列(一)

Apache Shiro 是一個強大而靈活的開源安全框架,它乾淨利落地處理身份認證,授權,企業會話管理和加密。
Apache Shiro 的首要目標是易於使用和理解。安全有時候是很複雜的,甚至是痛苦的,但它沒有必要這樣。框架應該儘可能掩蓋複雜的地方,露出一個乾淨而直觀的 API,來簡化開發人員在使他們的應用程序安全上的努力。
以下是你可以用 Apache Shiro 所做的事情:
驗證用戶來覈實他們的身份
對用戶執行訪問控制,如:
判斷用戶是否被分配了一個確定的安全角色
判斷用戶是否被允許做某事
在任何環境下使用 Session API,即使沒有 Web 或 EJB 容器
在身份驗證,訪問控制期間或在會話的生命週期,對事件作出反應。
聚集一個或多個用戶安全數據的數據源,並作爲一個單一的複合用戶“視圖”。

啓用單點登錄(SSO)功能。

併發登錄管理(一個賬號多人登錄作踢人操作)

爲沒有關聯到登錄的用戶啓用"Remember Me"服務

以及更多——全部集成到緊密結合的易於使用的 API 中。

目前Java領域主流的安全框架有SpringSecurity和Shiro,相比於SpringSecurity,Shiro輕量化,簡單容易上手,且不侷限於Java和Spring;SpringSecurity太笨重了,難以上手,且只能在Spring裏用,所以博主極力推薦Shiro。

spring集成shiro要用到shiro-all-1.2.4.jar

jar包下載地址:http://download.csdn.net/detail/qq_33556185/9540257

第一步:配置shiro.xml文件

shiro.xml配置文件代碼:

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
  5.     http://www.springframework.org/schema/beans/spring-beans-4.2.xsd     
  6.     http://www.springframework.org/schema/tx     
  7.     http://www.springframework.org/schema/tx/spring-tx-4.2.xsd    
  8.     http://www.springframework.org/schema/context    
  9.     http://www.springframework.org/schema/context/spring-context-4.2.xsd    
  10.     http://www.springframework.org/schema/mvc    
  11.     http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">  
  12.      <!-- Shiro Filter 攔截器相關配置 -->    
  13.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
  14.         <!-- securityManager -->    
  15.         <property name="securityManager" ref="securityManager" />    
  16.         <!-- 登錄路徑 -->    
  17.         <property name="loginUrl" value="/toLogin" />    
  18.         <!-- 用戶訪問無權限的鏈接時跳轉此頁面  -->    
  19.         <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />    
  20.         <!-- 過濾鏈定義 -->    
  21.         <property name="filterChainDefinitions">    
  22.             <value>    
  23.                 /loginin=anon  
  24.                 /toLogin=anon  
  25.                 /css/**=anon   
  26.                 /html/**=anon   
  27.                 /images/**=anon  
  28.                 /js/**=anon   
  29.                 /upload/**=anon   
  30.                 <!-- /userList=roles[admin] -->  
  31.                 /userList=authc,perms[/userList]  
  32.                 /toDeleteUser=authc,perms[/toDeleteUser]  
  33.                 /** = authc  
  34.              </value>    
  35.         </property>    
  36.     </bean>    
  37.     
  38.     <!-- securityManager -->    
  39.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
  40.         <property name="realm" ref="myRealm" />    
  41.     </bean>    
  42.     <!-- 自定義Realm實現 -->   
  43.     <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />    
  44.       
  45.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  46.       
  47.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
  48.        <property name="prefix" value="/"/>    
  49.        <property name="suffix" value=".jsp"></property>    
  50.     </bean>  
  51.       
  52. </beans>    

anno代表不需要授權即可訪問,對於靜態資源,訪問權限都設置爲anno

authc表示需要登錄纔可訪問

/userList=roles[admin]的含義是要訪問/userList需要有admin這個角色,如果沒有此角色訪問此URL會返回無授權頁面

/userList=authc,perms[/userList]的含義是要訪問/userList需要有/userList的權限,要是沒分配此權限訪問此URL會返回無授權頁面

[html] view plain copy
  1. <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />   
這個是業務對象,需要我們去實現。

第二步:在web.xml文件里加載shiro.xml,和加載其他配置文件是一樣的,就不多說了

[html] view plain copy
  1. <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>  
  4.         classpath*:/spring/spring-common.xml,  
  5.         classpath*:/spring/shiro.xml  
  6.     </param-value>  
  7. </context-param>  

第三步:配置shiroFilter,所有請求都要先進shiro的代理類

[html] view plain copy
  1.     <!--  
  2.       DelegatingFilterProxy類是一個代理類,所有的請求都會首先發到這個filter代理  
  3.                     然後再按照"filter-name"委派到spring中的這個bean。  
  4.                     在Spring中配置的bean的name要和web.xml中的<filter-name>一樣.  
  5.    targetFilterLifecycle,是否由spring來管理bean的生命週期,設置爲true有個好處,可以調用spring後續的bean  
  6. -->  
  7.    <filter>    
  8.     <filter-name>shiroFilter</filter-name>    
  9.     <filter-class>    
  10.         org.springframework.web.filter.DelegatingFilterProxy    
  11.     </filter-class>    
  12.          <init-param>    
  13.     <param-name>targetFilterLifecycle</param-name>    
  14.     <param-value>true</param-value>    
  15.     </init-param>    
  16.   </filter>    
  17.   
  18. <filter-mapping>    
  19.     <filter-name>shiroFilter</filter-name>    
  20.     <url-pattern>/*</url-pattern>    
  21. </filter-mapping>    
第四步:自定義realm
[java] view plain copy
  1. package com.core.shiro.realm;  
  2.   
  3. import java.util.List;  
  4. import javax.annotation.Resource;  
  5. import org.apache.shiro.authc.AuthenticationException;  
  6. import org.apache.shiro.authc.AuthenticationInfo;  
  7. import org.apache.shiro.authc.AuthenticationToken;  
  8. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  9. import org.apache.shiro.authc.UsernamePasswordToken;  
  10. import org.apache.shiro.authz.AuthorizationInfo;  
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  12. import org.apache.shiro.realm.AuthorizingRealm;  
  13. import org.apache.shiro.subject.PrincipalCollection;  
  14. import org.springframework.util.StringUtils;  
  15. import com.core.shiro.dao.IPermissionDao;  
  16. import com.core.shiro.dao.IRoleDao;  
  17. import com.core.shiro.dao.IUserDao;  
  18. import com.core.shiro.entity.Permission;  
  19. import com.core.shiro.entity.Role;  
  20. import com.core.shiro.entity.User;  
  21. public class CustomRealm extends AuthorizingRealm{    
  22.     @Resource  
  23.     private IUserDao userDao;  
  24.     @Resource  
  25.     private IPermissionDao permissionDao;  
  26.     @Resource  
  27.     private IRoleDao roleDao;  
  28.       
  29.     /** 
  30.      * 添加角色 
  31.      * @param username 
  32.      * @param info 
  33.      */  
  34.     private void addRole(String username, SimpleAuthorizationInfo info) {  
  35.         List<Role> roles = roleDao.findByUser(username);  
  36.         if(roles!=null&&roles.size()>0){  
  37.             for (Role role : roles) {  
  38.                 info.addRole(role.getRoleName());  
  39.             }  
  40.         }  
  41.     }  
  42.   
  43.     /** 
  44.      * 添加權限 
  45.      * @param username 
  46.      * @param info 
  47.      * @return 
  48.      */  
  49.     private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) {  
  50.         List<Permission> permissions = permissionDao.findPermissionByName(username);  
  51.         for (Permission permission : permissions) {  
  52.             info.addStringPermission(permission.getUrl());//添加權限    
  53.         }  
  54.         return info;    
  55.     }    
  56.     
  57.       
  58.     /** 
  59.      * 獲取授權信息 
  60.      */  
  61.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {    
  62.         //用戶名    
  63.         String username = (String) principals.fromRealm(getName()).iterator().next();   
  64.         //根據用戶名來添加相應的權限和角色  
  65.         if(!StringUtils.isEmpty(username)){  
  66.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
  67.             addPermission(username,info);  
  68.             addRole(username, info);  
  69.             return info;  
  70.         }  
  71.         return null;    
  72.     }  
  73.   
  74.      
  75.    /**  
  76.     * 登錄驗證  
  77.     */    
  78.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {    
  79.         //令牌——基於用戶名和密碼的令牌    
  80.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;    
  81.         //令牌中可以取出用戶名  
  82.         String accountName = token.getUsername();  
  83.         //讓shiro框架去驗證賬號密碼  
  84.         if(!StringUtils.isEmpty(accountName)){  
  85.             User user = userDao.findUser(accountName);  
  86.             if(user != null){  
  87.             return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());  
  88.             }  
  89.         }  
  90.           
  91.         return null;  
  92.     }    
  93.     
  94. }    
第五步:控制層代碼
[java] view plain copy
  1. package com.core.shiro.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import org.apache.shiro.SecurityUtils;  
  5. import org.apache.shiro.authc.AuthenticationException;  
  6. import org.apache.shiro.authc.UsernamePasswordToken;  
  7. import org.apache.shiro.crypto.hash.Md5Hash;  
  8. import org.apache.shiro.subject.Subject;  
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. @Controller  
  12. public class ShiroAction {  
  13.     @RequestMapping("loginin")  
  14.     public String login(HttpServletRequest request){  
  15.          //當前Subject    
  16.          Subject currentUser = SecurityUtils.getSubject();    
  17.          //加密(md5+鹽),返回一個32位的字符串小寫  
  18.          String salt="("+request.getParameter("username")+")";    
  19.          String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();  
  20.          //傳遞token給shiro的realm  
  21.          UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("username"),md5Pwd);    
  22.          try {    
  23.              currentUser.login(token);   
  24.              return "welcome";  
  25.            
  26.          } catch (AuthenticationException e) {//登錄失敗    
  27.              request.setAttribute("msg""用戶名和密碼錯誤");    
  28.          }   
  29.             return "login";  
  30.     }  
  31.     @RequestMapping("toLogin")  
  32.     public String toLogin(){  
  33.          return "login";  
  34.     }  
  35. }  

第六步:login頁面 略

     login請求調用currentUser.login之後,shiro會將token傳遞給自定義realm,此時realm會先調用doGetAuthenticationInfo(AuthenticationToken authcToken )登錄驗證的方法,驗證通過後會接着調用 doGetAuthorizationInfo(PrincipalCollection principals)獲取角色和權限的方法(授權),最後返回視圖。   

     當其他請求進入shiro時,shiro會調用doGetAuthorizationInfo(PrincipalCollection principals)去獲取授權信息,若是沒有權限或角色,會跳轉到未授權頁面,若有權限或角色,shiro會放行,ok,此時進入真正的請求方法……

到此shiro的認證及授權便完成了。


 

Shiro安全框架入門篇(登錄驗證實例詳解與源碼)


一、Shiro框架簡單介紹

Apache Shiro是Java的一個安全框架,旨在簡化身份驗證和授權。Shiro在JavaSE和JavaEE項目中都可以使用。它主要用來處理身份認證,授權,企業會話管理和加密等。Shiro的具體功能點如下:

(1)身份認證/登錄,驗證用戶是不是擁有相應的身份; 
(2)授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能做事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具有某個權限; 
(3)會話管理,即用戶登錄後就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通JavaSE環境的,也可以是如Web環境的; 
(4)加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲; 
(5)Web支持,可以非常容易的集成到Web環境; 
Caching:緩存,比如用戶登錄後,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率; 
(6)shiro支持多線程應用的併發驗證,即如在一個線程中開啓另一個線程,能把權限自動傳播過去; 
(7)提供測試支持; 
(8)允許一個用戶假裝爲另一個用戶(如果他們允許)的身份進行訪問; 
(9)記住我,這個是非常常見的功能,即一次登錄後,下次再來的話不用登錄了。

文字描述可能並不能讓猿友們完全理解具體功能的意思。下面我們以登錄驗證爲例,向猿友們介紹Shiro的使用。至於其他功能點,猿友們用到的時候再去深究其用法也不遲。

二、Shiro實例詳細說明

本實例環境:eclipse + maven 
本實例採用的主要技術:spring + springmvc + shiro

2.1、依賴的包

假設已經配置好了spring和springmvc的情況下,還需要引入shiro以及shiro集成到spring的包,maven依賴如下:

<!-- Spring 整合Shiro需要的依賴 -->  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-core</artifactId>  
    <version>1.2.1</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-web</artifactId>  
    <version>1.2.1</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-ehcache</artifactId>  
    <version>1.2.1</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.shiro</groupId>  
    <artifactId>shiro-spring</artifactId>  
    <version>1.2.1</version>  
</dependency>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2.2、定義shiro攔截器

對url進行攔截,如果沒有驗證成功的需要驗證,然後額外給用戶賦予角色和權限。

自定義的攔截器需要繼承AuthorizingRealm並實現登錄驗證和賦予角色權限的兩個方法,具體代碼如下:

package com.luo.shiro.realm;

import java.util.HashSet;
import java.util.Set;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.luo.util.DecriptUtil;

public class MyShiroRealm extends AuthorizingRealm {

    //這裏因爲沒有調用後臺,直接默認只有一個用戶("luoguohui","123456")
    private static final String USER_NAME = "luoguohui";  
    private static final String PASSWORD = "123456";  

    /* 
     * 授權
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
        Set<String> roleNames = new HashSet<String>();  
        Set<String> permissions = new HashSet<String>();  
        roleNames.add("administrator");//添加角色
        permissions.add("newPage.jhtml");  //添加權限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
        info.setStringPermissions(permissions);  
        return info;  
    }

    /* 
     * 登錄驗證
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        if(token.getUsername().equals(USER_NAME)){
            return new SimpleAuthenticationInfo(USER_NAME, DecriptUtil.MD5(PASSWORD), getName());  
        }else{
            throw new AuthenticationException();  
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

2.3、shiro配置文件

spring-shiro.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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
    default-lazy-init="true">  

    <description>Shiro Configuration</description>  

    <!-- Shiro's main business-tier object for web-enabled applications -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myShiroRealm" />  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- 項目自定義的Realm -->  
    <bean id="myShiroRealm" class="com.luo.shiro.realm.MyShiroRealm">  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- Shiro Filter -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <property name="securityManager" ref="securityManager" />  
        <property name="loginUrl" value="/login.jhtml" />  
        <property name="successUrl" value="/loginsuccess.jhtml" />  
        <property name="unauthorizedUrl" value="/error.jhtml" />  
        <property name="filterChainDefinitions">  
            <value>  
                /index.jhtml = authc  
                /login.jhtml = anon
                /checkLogin.json = anon  
                /loginsuccess.jhtml = anon  
                /logout.json = anon  
                /** = authc  
            </value>  
        </property>  
    </bean>  

    <!-- 用戶授權信息Cache -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  

    <!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->  
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  

    <!-- AOP式方法級權限檢查 -->  
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
        depends-on="lifecycleBeanPostProcessor">  
        <property name="proxyTargetClass" value="true" />  
    </bean>  

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>  

</beans>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

這裏有必要說清楚”shiroFilter” 這個bean裏面的各個屬性property的含義:

(1)securityManager:這個屬性是必須的,沒什麼好說的,就這樣配置就好。 
(2)loginUrl:沒有登錄的用戶請求需要登錄的頁面時自動跳轉到登錄頁面,可配置也可不配置。 
(3)successUrl:登錄成功默認跳轉頁面,不配置則跳轉至”/”,一般可以不配置,直接通過代碼進行處理。 
(4)unauthorizedUrl:沒有權限默認跳轉的頁面。 
(5)filterChainDefinitions,對於過濾器就有必要詳細說明一下:

1)Shiro驗證URL時,URL匹配成功便不再繼續匹配查找(所以要注意配置文件中的URL順序,尤其在使用通配符時),故filterChainDefinitions的配置順序爲自上而下,以最上面的爲準

2)當運行一個Web應用程序時,Shiro將會創建一些有用的默認Filter實例,並自動地在[main]項中將它們置爲可用自動地可用的默認的Filter實例是被DefaultFilter枚舉類定義的,枚舉的名稱字段就是可供配置的名稱

3)通常可將這些過濾器分爲兩組:

anon,authc,authcBasic,user是第一組認證過濾器

perms,port,rest,roles,ssl是第二組授權過濾器

注意user和authc不同:當應用開啓了rememberMe時,用戶下次訪問時可以是一個user,但絕不會是authc,因爲authc是需要重新認證的 
user表示用戶不一定已通過認證,只要曾被Shiro記住過登錄狀態的用戶就可以正常發起請求,比如rememberMe

說白了,以前的一個用戶登錄時開啓了rememberMe,然後他關閉瀏覽器,下次再訪問時他就是一個user,而不會authc

4)舉幾個例子 
/admin=authc,roles[admin] 表示用戶必需已通過認證,並擁有admin角色纔可以正常發起’/admin’請求 
/edit=authc,perms[admin:edit] 表示用戶必需已通過認證,並擁有admin:edit權限纔可以正常發起’/edit’請求 
/home=user 表示用戶不一定需要已經通過認證,只需要曾經被Shiro記住過登錄狀態就可以正常發起’/home’請求

5)各默認過濾器常用如下(注意URL Pattern裏用到的是兩顆星,這樣才能實現任意層次的全匹配) 
/admins/**=anon 無參,表示可匿名使用,可以理解爲匿名用戶或遊客 
/admins/user/**=authc 無參,表示需認證才能使用 
/admins/user/**=authcBasic 無參,表示httpBasic認證 
/admins/user/**=user 無參,表示必須存在用戶,當登入操作時不做檢查 
/admins/user/**=ssl 無參,表示安全的URL請求,協議爲https 
/admins/user/*=perms[user:add:
參數可寫多個,多參時必須加上引號,且參數之間用逗號分割,如/admins/user/*=perms[“user:add:,user:modify:*”] 
當有多個參數時必須每個參數都通過纔算通過,相當於isPermitedAll()方法 
/admins/user/**=port[8081] 
當請求的URL端口不是8081時,跳轉到schemal://serverName:8081?queryString 
其中schmal是協議http或https等,serverName是你訪問的Host,8081是Port端口,queryString是你訪問的URL裏的?後面的參數 
/admins/user/**=rest[user] 
根據請求的方法,相當於/admins/user/**=perms[user:method],其中method爲post,get,delete等 
/admins/user/**=roles[admin] 
參數可寫多個,多個時必須加上引號,且參數之間用逗號分割,如/admins/user/**=roles[“admin,guest”] 
當有多個參數時必須每個參數都通過纔算通過,相當於hasAllRoles()方法

上文參考了http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html,更多詳細說明請訪問該鏈接。

2.4、web.xml配置引入對應的配置文件和過濾器

<!-- 讀取spring和shiro配置文件 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>
</context-param>

<!-- shiro過濾器 -->
<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>*.jhtml</url-pattern>  
    <url-pattern>*.json</url-pattern>  
</filter-mapping> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2.5、controller代碼

package com.luo.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;
import com.luo.errorcode.LuoErrorCode;
import com.luo.exception.BusinessException;
import com.luo.util.DecriptUtil;

@Controller
public class UserController {

    @RequestMapping("/index.jhtml")
    public ModelAndView getIndex(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

    @RequestMapping("/exceptionForPageJumps.jhtml")
    public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
        throw new BusinessException(LuoErrorCode.NULL_OBJ);
    }

    @RequestMapping(value="/businessException.json", method=RequestMethod.POST)
    @ResponseBody  
    public String businessException(HttpServletRequest request) {
        throw new BusinessException(LuoErrorCode.NULL_OBJ);
    }

    @RequestMapping(value="/otherException.json", method=RequestMethod.POST)
    @ResponseBody  
    public String otherException(HttpServletRequest request) throws Exception {
        throw new Exception();
    }

    //跳轉到登錄頁面
    @RequestMapping("/login.jhtml")
    public ModelAndView login() throws Exception {
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }

    //跳轉到登錄成功頁面
    @RequestMapping("/loginsuccess.jhtml")
    public ModelAndView loginsuccess() throws Exception {
        ModelAndView mav = new ModelAndView("loginsuccess");
        return mav;
    }

    @RequestMapping("/newPage.jhtml")
    public ModelAndView newPage() throws Exception {
        ModelAndView mav = new ModelAndView("newPage");
        return mav;
    }

    @RequestMapping("/newPageNotAdd.jhtml")
    public ModelAndView newPageNotAdd() throws Exception {
        ModelAndView mav = new ModelAndView("newPageNotAdd");
        return mav;
    }

    /** 
     * 驗證用戶名和密碼 
     * @param String username,String password
     * @return 
     */  
    @RequestMapping(value="/checkLogin.json",method=RequestMethod.POST)  
    @ResponseBody  
    public String checkLogin(String username,String password) {  
        Map<String, Object> result = new HashMap<String, Object>();
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(password));  
            Subject currentUser = SecurityUtils.getSubject();  
            if (!currentUser.isAuthenticated()){
                //使用shiro來驗證  
                token.setRememberMe(true);  
                currentUser.login(token);//驗證角色和權限  
            } 
        }catch(Exception ex){
            throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE);
        }
        result.put("success", true);
        return JSONUtils.toJSONString(result);  
    }  

    /** 
     * 退出登錄
     */  
    @RequestMapping(value="/logout.json",method=RequestMethod.POST)    
    @ResponseBody    
    public String logout() {   
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        Subject currentUser = SecurityUtils.getSubject();       
        currentUser.logout();    
        return JSONUtils.toJSONString(result);
    }  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111

上面代碼,我們只需要更多地關注登錄驗證和退出登錄的代碼。 
其中DecriptUtil.MD5(password),對密碼進行md5加密解密是我自己寫的工具類DecriptUtil,對應MyShiroRealm裏面的登錄驗證裏面也有對應對應的方法。 
另外,BusinessException是我自己封裝的異常類。 
最後會提供整個工程源碼供猿友下載,裏面包含了所有的代碼。

2.6、login.jsp代碼

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<script src="<%=request.getContextPath()%>/static/bui/js/jquery-1.8.1.min.js"></script>
</head>
<body>
username: <input type="text" id="username"><br><br>  
password: <input type="password" id="password"><br><br>
<button id="loginbtn">登錄</button>
</body>
<script type="text/javascript">
$('#loginbtn').click(function() {
    var param = {
        username : $("#username").val(),
        password : $("#password").val()
    };
    $.ajax({ 
        type: "post", 
        url: "<%=request.getContextPath()%>" + "/checkLogin.json", 
        data: param, 
        dataType: "json", 
        success: function(data) { 
            if(data.success == false){
                alert(data.errorMsg);
            }else{
                //登錄成功
                window.location.href = "<%=request.getContextPath()%>" +  "/loginsuccess.jhtml";
            }
        },
        error: function(data) { 
            alert("調用失敗...."); 
        }
    });
});
</script>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

2.7、效果演示

(1)如果未登錄前,輸入http://localhost:8080/web_exception_project/index.jhtml會自動跳轉到http://localhost:8080/web_exception_project/login.jhtml

(2)如果登錄失敗和登錄成功:

這裏寫圖片描述

這裏寫圖片描述

(3)如果登錄成功,訪問http://localhost:8080/web_exception_project/index.jhtml就可以到其對應的頁面了。

這裏寫圖片描述

2.8、源碼下載

http://download.csdn.net/detail/u013142781/9426670

2.9、我遇到的坑

在本實例的調試裏面遇到一個問題,雖然跟shiro沒有關係,但是也跟猿友們分享一下。 
就是ajax請求設置了“contentType : “application/json””,導致controller獲取不到username和password這兩個參數。 
後面去掉contentType : “application/json”,採用默認的就可以了。

具體原因可以瀏覽博文:http://blog.csdn.net/mhmyqn/article/details/25561535




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章