Shiro+Spring整合(超詳細,有demo)

剛剛看了Shiro的入門視頻,學習了了Shiro的一些知識,感謝Java_小鋒老師的學習視頻,在這裏我分享一下我的學習心得,同時算對自己這倆天學習的總結,同時將Shiro整合到Spring中。
好了,我簡單說一下大概需要學習的東西吧。Shiro的官網上的知識點很多。作爲入門,可以先記住Shiro核心的點
1、權限認證
這裏寫圖片描述
2、授權
這裏寫圖片描述
3、permissions權限
這裏寫圖片描述
4、Realm

現在開始配置:
第一步:配置Web.xml, shiro核心的配置就是第一個。所有的過濾都會經過org.springframework.web.filter.DelegatingFilterProxy

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MyWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

    <!-- shiro過濾器定義 ,一定要放在最前面-->
    <filter>  
        <filter-name>shiroFilter</filter-name>  
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    <init-param>  
    <!-- 該值缺省爲false,表示生命週期由SpringApplicationContext管理,設置爲true則表示由ServletContainer管理 -->  
    <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>


    <!-- Spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 編碼過濾器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Spring監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 添加對springmvc的支持 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>


</web-app>

第二步:配置applicationContext.xml,都有註釋,其中Shiro連接約束配置就體現了,Shiro中的權限認證
和permissions權限的問題,請注意shiro過濾器裏面的內容,後面我們會按照身份驗證,角色驗證和權限驗證去演示。我已經提前在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:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    

    <!-- 自動掃描 -->
    <context:component-scan base-package="com.web.*.service" />

    <!-- 配置數據源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/tes_shiro"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!-- 配置mybatis的sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mappers.xml文件 -->
        <property name="mapperLocations" value="classpath:com/web/mapper/*.xml"></property>
        <!-- mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

    </bean>

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.web.*.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

     <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類爲自定義的MyRealm.java -->
    <bean id="myRealm" class="com.web.demo.util.MyRealm"/>  

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
      <property name="realm" ref="myRealm"/>   
    </bean>  

    <!-- Shiro過濾器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <!-- Shiro的核心安全接口,這個屬性是必須的 -->  
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->  
        <property name="loginUrl" value="/index.jsp"/>
        <!-- 權限認證失敗,則跳轉到指定頁面 -->  
        <property name="unauthorizedUrl" value="/unauthor.jsp"/>  
        <!-- Shiro連接約束配置,即過濾鏈的定義 -->  
        <property name="filterChainDefinitions">  
            <value>  
                <!-- 執行/login的時候不需要任何身份 -->
                 /login=anon  
                 <!-- 訪問/admin*需要身份認證(既登錄),admin*有點通配符的意思,就是admin或者admin1,admin2等,任何以admin開頭的都需要身份認證-->
                /admin*=authc 
                <!-- 訪問/student需要角色爲teacher才行 -->
                /user/student=roles[teacher]
                <!-- 訪問/teacher需要有創建權限 -->
                /teacher=perms["user:create"]
            </value>  
        </property>
    </bean>  

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

    <!-- 開啓Shiro註解 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>  
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
      <property name="securityManager" ref="securityManager"/>  
    </bean>  

    <!-- 配置事務通知屬性 -->  
    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
        <!-- 定義事務傳播屬性 -->  
        <tx:attributes>  
            <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="new*" propagation="REQUIRED" />  
            <tx:method name="set*" propagation="REQUIRED" />  
            <tx:method name="remove*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="change*" propagation="REQUIRED" />  
            <tx:method name="check*" propagation="REQUIRED" />  
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="*" propagation="REQUIRED" read-only="true" />  
        </tx:attributes>  
    </tx:advice>  

    <!-- 配置事務切面 -->  
    <aop:config>  
        <aop:pointcut id="serviceOperation"  
            expression="execution(* com.web.*.service.*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
    </aop:config>  


</beans>

第三步:我們需要自定義的MyRealm,代碼如下:

package com.web.demo.util;


import javax.annotation.Resource;

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.web.demo.model.User;
import com.web.demo.service.UserService;


public class MyRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    /**
     * 爲當前登錄的賬號授予角色和權限
     * 描述:此方法是繼承AuthorizingRealm,所有的信息都是封裝
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 封裝角色信息
        authorizationInfo.setRoles(userService.getRoles(userName));
        // 封裝權限信息
        authorizationInfo.setStringPermissions(userService
                .getPermissions(userName));
        return authorizationInfo;
    }

    /**
     * 驗證當前登錄的用戶
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName=(String)token.getPrincipal();
            User user=userService.getByUserName(userName);
            if(user!=null){
                //參數說明,參數1:數據庫獲取用戶名 ,參數2:數據庫獲取的密碼,參數3:RealmName,這個隨便起,無所謂。將這些參數傳入,與用戶輸入的進行對比
                AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
                return authcInfo;
            }else{
                return null;                
            }
    }

}

第四步:controller層的測試代碼

package com.web.demo.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.web.demo.model.User;




/**
 * 用戶Controller層
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {


    /**
     * 用戶登錄
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(User user,HttpServletRequest request){
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(), user.getPassword());
        try{
            subject.login(token);
            Session session=subject.getSession();
            System.out.println("sessionId:"+session.getId());
            System.out.println("sessionHost:"+session.getHost());
            System.out.println("sessionTimeout:"+session.getTimeout());
            session.setAttribute("info", "session的數據");
            return "redirect:/success.jsp";
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("user", user);
            request.setAttribute("errorMsg", "用戶名或密碼錯誤!");
            return "index";
        }
    }



    @RequestMapping("/student")
    public String student(User user,HttpServletRequest request){
        return "redirect:/demo/jsp/student.jsp";
    }



}

第五步:success.jsp和student.jsp頁面,

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!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>Insert title here</title>
</head>
<body>
${info }
歡迎你!
<shiro:hasRole name="admin">
    歡迎有admin角色的用戶!<shiro:principal/>
</shiro:hasRole>
<shiro:hasPermission name="student:create">
    歡迎有student:create權限的用戶!<shiro:principal/>
</shiro:hasPermission>
</body>
</html>

上面是success.jsp代碼。注意shiro也有jsp標籤,比如就是判斷當前頁面用戶是否是admin角色,比如判斷當前用戶是否擁有教師角色下的創建權限

student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!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></title>
</head>
<body>

您好,老師!我是role爲teacher才能進入的頁面
<%-- <shiro:hasRole name="admin">
    歡迎有admin角色的用戶!<shiro:principal/>
</shiro:hasRole>
<shiro:hasPermission name="student:create">
    歡迎有student:create權限的用戶!<shiro:principal/>
</shiro:hasPermission> --%>
</body>
</html>

好了,核心代碼基本是貼完了,我這邊演示一下,主要從身份驗證,角色驗證,權限驗證三個方面去演示。

1、身份驗證,測試。

我們先不登陸,直接訪問controller,試試,會發現強制進入登陸頁面,這就是身份驗證

這裏寫圖片描述

2、角色驗證,我們寫了一個只有擁有teacher的過濾,(見applicationContext.xml中的shiro過濾配置)。只有role爲teacher的可以進入,測試。

我們先用role爲admin的用戶進入。
這裏寫圖片描述

然後在瀏覽器裏面直接輸入:http://localhost:8080/MyWeb/user/student 會出現下面情況(權限不足),
這裏寫圖片描述
unauthor.jsp是隻有權限不足的情況下才會提示的頁面。

我們再換role爲teacher的用戶登錄、
這裏寫圖片描述

然後再訪問http://localhost:8080/MyWeb/user/student (權限驗證成功,可以訪問)
這裏寫圖片描述

3.權限驗證。在success.jsp中就有體現,發現admin和tea倆個用戶登錄之後的頁面顯示內容是不一樣的。

admin登錄後的樣子:
這裏寫圖片描述

tea登錄後的樣子
這裏寫圖片描述

好了,暫時就到這麼多了,我把我測試的Deam和數據庫表上傳上來,有興趣的可以下載看看。我的項目是Maven的。如果本地沒有配置Maven的需要先提前配置好Maven環境。

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