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="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.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

    <!-- dataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <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 id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>

    <!-- 數據庫保存的密碼是使用MD5算法加密的,所以這裏需要配置一個密碼匹配對象 -->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>

    <!-- 緩存管理 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>

    <!-- 
      使用Shiro自帶的JdbcRealm類
      指定密碼匹配所需要用到的加密對象
      指定存儲用戶、角色、權限許可的數據源及相關查詢語句
     -->
    <bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
        <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 id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="jdbcRealm"></property>
        <property name="cacheManager" ref="cacheManager"></property>
    </bean>

    <!-- 
       Shiro主過濾器本身功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行
       Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支持 
    -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 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
        class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
    <bean
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"></property>
    </bean>
    -->
</beans>

上述代碼中已經對每個java bean的用途做了詳細的註釋說明,這裏僅對FilterChain過濾鏈的定義詳細闡述一下:
測試用例中對/security/*的訪問是不需要認證控制的,這主要是用於用戶登錄和退出的
測試用例中對/tag的訪問是需要認證控制的,就是說只有通過認證的用戶纔可以訪問該資源。如果用戶直接在地址欄中訪問http://localhost:8880/learning/tag,系統會自動跳轉至登錄頁面,要求用戶先進行身份認證。
完成這兩步之後,我們可以Run一下程序,如果可以看到以下頁面,就表明我們的配置文件沒有錯誤,Shiro和Spring MVC的整合已經完成了。後繼的步驟可以視爲是對整合後的框進行的一個測試。

第三步,編寫登錄頁面和後臺代碼

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://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 id="" 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";
    }

如果輸入不存在的用戶名或是錯誤的密碼界面上會有相應的提示信息。

參考:http://blog.csdn.net/chris_mao/article/details/49288251

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