閱讀438 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Shiro係列之Shiro+Spring MVC整合

第一步,Shiro Filter

在web.xml文件中增加以下代碼,確保Web項目中需要權限管理的URL都可以被Shiro攔截過濾。


<!-- Shiro Filter -->  
    <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> 

通常將這段代碼中的filter-mapping放在所有filter-mapping之前,以達到shiro是第一個對web請求進行攔截過濾之目的。這裏的fileter-name應該要和第二步中配置的Java bean的id一致。

第二步,配置各種Java Bean

在root-context.xml文件中配置Shiro


    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="https://www.springframework.org/schema/beans"  
        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">  
      
        <!-- Root Context: defines shared resources visible to all other web components -->  
      
        <!-- dataSource -->  
        <bean   
            >  
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/etao_java" />  
            <property name="username" value="root" />  
            <property name="password" value="cope9020" />  
        </bean>  
      
        <bean  ></bean>  
      
        <!-- 數據庫保存的密碼是使用MD5算法加密的,所以這裏需要配置一個密碼匹配對象 -->  
        <bean  ></bean>  
      
        <!-- 緩存管理 -->  
        <bean  ></bean>  
      
        <!--   
          使用Shiro自帶的JdbcRealm類  
          指定密碼匹配所需要用到的加密對象  
          指定存儲用戶、角色、權限許可的數據源及相關查詢語句  
         -->  
        <bean  >  
            <property name="credentialsMatcher" ref="credentialsMatcher"></property>  
            <property name="permissionsLookupEnabled" value="true"></property>  
            <property name="dataSource" ref="dataSource"></property>  
            <property name="authenticationQuery"  
                value="SELECT password FROM sec_user WHERE user_name = ?"></property>  
            <property name="userRolesQuery"  
                value="SELECT role_name from sec_user_role left join sec_role using(role_id) left join sec_user using(user_id) WHERE user_name = ?"></property>  
            <property name="permissionsQuery"  
                value="SELECT permission_name FROM sec_role_permission left join sec_role using(role_id) left join sec_permission using(permission_id) WHERE role_name = ?"></property>  
        </bean>  
      
        <!-- Shiro安全管理器 -->  
        <bean  >  
            <property name="realm" ref="jdbcRealm"></property>  
            <property name="cacheManager" ref="cacheManager"></property>  
        </bean>  
      
        <!--   
           Shiro主過濾器本身功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行  
           Web應用中,Shiro可控製的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支持   
        -->  
        <bean  >  
            <!-- Shiro的核心安全接口,這個屬性是必須的 -->  
            <property name="securityManager" ref="securityManager"></property>  
            <!-- 要求登錄時的鏈接(登錄頁麵地址),非必須的屬性,默認會自動尋找Web工程根目錄下的"/login.jsp"頁麵 -->  
            <property name="loginUrl" value="/security/login"></property>  
            <!-- 登錄成功後要跳轉的連接(本例中此屬性用不到,因為登錄成功後的處理邏輯在LoginController裏硬編碼) -->  
            <!-- <property name="successUrl" value="/" ></property> -->  
            <!-- 用戶訪問未對其授權的資源時,所顯示的連接 -->  
            <property name="unauthorizedUrl" value="/"></property>  
            <property name="filterChainDefinitions">  
                <value>  
                    /security/*=anon  
                    /tag=authc  
                </value>  
            </property>  
        </bean>  
      
        <!--   
           開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,  
           並在必要時進行安全邏輯驗證  
        -->  
        <!--  
        <bean  
            ></bean>  
        <bean  
            >  
            <property name="securityManager" ref="securityManager"></property>  
        </bean>  
        -->  
    </beans>  

上述代碼中已經對每個java bean的用途做了詳細的注釋說明,這裏僅對FilterChain過濾鏈的定義詳細闡述一下:

  • 測試用例中對/security/*的訪問是不需要認證控製的,這主要是用於用戶登錄和退出的
  • 測試用例中對/tag的訪問是需要認證控製的,就是說隻有通過認證的用戶才可以訪問該資源。如果用戶直接在地址欄中訪問https://localhost:8880/learning/tag,係統會自動跳轉至登錄頁麵,要求用戶先進行身份認證。

完成這兩步之後,我們可以Run一下程序,如果可以看到以下頁麵,就表明我們的配置文件沒有錯誤,Shiro和spring MVC的整合已經完成了。後繼的步驟可以視為是對整合後的框進行的一個測試




    <%@ page language="java" contentType="text/html; charset=UTF-8"  
        pageEncoding="UTF-8"%>  
    <%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>  
      
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Login Page</title>  
    </head>  
    <body>  
        <h1>login page</h1>  
        <form  action="dologin" method="post">  
            <label>User Name</label> <input tyep="text" name="userName"  
                maxLength="40" /> <label>Password</label><input type="password"  
                name="password" /> <input type="submit" value="login" />  
        </form>  
        <%--用於輸入後台返回的驗證錯誤信息 --%>  
        <P><c:out value="${message }" /></P>  
    </body>  
    </html>  

後台登錄代碼


    /** 
     * 實際的登錄代碼 
     * 如果登錄成功,跳轉至首頁;登錄失敗,則將失敗信息反饋對用戶 
     *  
     * @param request 
     * @param model 
     * @return 
     */  
    @RequestMapping(value = "/dologin")  
    public String doLogin(HttpServletRequest request, Model model) {  
        String msg = "";  
        String userName = request.getParameter("userName");  
        String password = request.getParameter("password");  
        System.out.println(userName);  
        System.out.println(password);  
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);  
        token.setRememberMe(true);  
        Subject subject = SecurityUtils.getSubject();  
        try {  
            subject.login(token);  
            if (subject.isAuthenticated()) {  
                return "redirect:/";  
            } else {  
                return "login";  
            }  
        } catch (IncorrectCredentialsException e) {  
            msg = "登錄密碼錯誤. Password for account " + token.getPrincipal() + " was incorrect.";  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (ExcessiveAttemptsException e) {  
            msg = "登錄失敗次數過多";  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (LockedAccountException e) {  
            msg = "帳號已被鎖定. The account for username " + token.getPrincipal() + " was locked.";  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (DisabledAccountException e) {  
            msg = "帳號已被禁用. The account for username " + token.getPrincipal() + " was disabled.";  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (ExpiredCredentialsException e) {  
            msg = "帳號已過期. the account for username " + token.getPrincipal() + "  was expired.";  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (UnknownAccountException e) {  
            msg = "帳號不存在. There is no user with username of " + token.getPrincipal();  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        } catch (UnauthorizedException e) {  
            msg = "您沒有得到相應的授權!" + e.getMessage();  
            model.addAttribute("message", msg);  
            System.out.println(msg);  
        }  
        return "login";  
    }  


 登錄成功後,會轉至首頁,並顯示出當前用戶名。


 登錄成功後,會轉至首頁,並顯示出當前用戶名。


最後更新:2017-07-07 14:33:49

  上一篇:go  虛擬主機租用和服務器租用的三大不同之處
  下一篇:go  菜鳥回應天貓國際直郵升級:僅搭建平台,商家可自主選擇推薦物流商