Shiro框架的配置和使用

URL權限過濾
shiro安全框架:
+ehcache緩存

1、引入依賴pom.xml

        <!-- Apache Shiro 權限架構 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.2.3</version>
        </dependency>

2、核心filter,一個filter相當於10個filter;web.xml

    注意:shiro的filter必須在struts2的filter之前,否則action無法創建

    <!-- Shiro Security filter  filter-name這個名字的值將來還會在spring中用到  -->
    <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>


3、在spring applicationContext.xml中記載shiro配置文件,放在事務管理器之前配置
<aop:aspectj-autoproxy proxy-target-class="true" />

同時添加專門配置shiro的配置文件
<import resource="spring/applicationContext-shiro.xml"/>

和ehcache支持ehcache-shiro.xml

<ehcache updateCheck="false" name="shiroCache">

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />
</ehcache>


4、applicationContext-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"       
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
    http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop    
    http://www.springframework.org/schema/aop/spring-aop.xsd    
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">

    <description>Shiro的配置</description>

    <!-- SecurityManager配置 -->
    <!-- 配置Realm域 -->
    <!-- 密碼比較器 -->
    <!-- 代理如何生成? 用工廠來生成Shiro的相關過濾器-->
    <!-- 配置緩存:ehcache緩存 -->
    <!-- 安全管理 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
        <property name="realm" ref="authRealm"/><!-- 引用自定義的realm -->
        <!-- 緩存 -->
        <property name="cacheManager" ref="shiroEhcacheManager"/>
    </bean>

    <!-- 自定義權限認證 -->
    <bean id="authRealm" class="cn.itcast.jk.shiro.AuthRealm">
        <property name="userService" ref="userService"/>
        <!-- 自定義密碼加密算法  -->
        <property name="credentialsMatcher" ref="passwordMatcher"/>
    </bean>

    <!-- 設置密碼加密策略 md5hash -->
    <bean id="passwordMatcher" class="cn.itcast.jk.shiro.CustomCredentialsMatcher"/>

    <!-- filter-name這個名字的值來自於web.xml中filter的名字 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--登錄頁面  -->
        <property name="loginUrl" value="/index.jsp"></property>
        <!-- 登錄成功後 -->      
        <property name="successUrl" value="/home.action"></property>
        <property name="filterChainDefinitions">
            <!-- /**代表下面的多級目錄也過濾 -->
            <value>
                /index.jsp* = anon
                /home* = anon
                /sysadmin/login/login.jsp* = anon
                /sysadmin/login/logout.jsp* = anon
                /login* = anon
                /logout* = anon
                /components/** = anon
                /css/** = anon
                /images/** = anon
                /js/** = anon
                /make/** = anon
                /skin/** = anon
                /stat/** = anon
                /ufiles/** = anon
                /validator/** = anon
                /resource/** = anon
                /** = authc
                /*.* = authc
            </value>
        </property>
    </bean>

    <!-- 用戶授權/認證信息Cache, 採用EhCache  緩存 -->
    <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
    </bean>

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

    <!-- 生成代理,通過代理進行控制 -->
    <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>


5、自定義realm  AuthRealm

在認證、授權內部實現機制中都有提到,最終處理都將交給Realm進行處理。
因爲在Shiro中,最終是通過Realm來獲取應用程序中的用戶、角色及權限信息的。
通常情況下,在Realm中會直接從我們的數據源中獲取Shiro需要的驗證信息。可以說,Realm是專用於安全框架的DAO.

public class AuthRealm extends AuthorizingRealm{
    private UserService userService;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //授權
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授權");
        //獲取當前用戶
        User user = (User)principals.fromRealm(getName()).iterator().next();
        //得到權限字符串
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<Role> roles = user.getRoles();
        List<String> list = new ArrayList();
        for(Role role :roles){
            Set<Module> modules = role.getModules();
            for(Module m:modules){
                if(m.getCtype()==0){
                    //說明是主菜單
                    list.add(m.getCpermission());
                }
            }
        }

        info.addStringPermissions(list);
        return info;
    }
    //認證  登錄
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        System.out.println("認證");
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;

        User user = userService.findUserByName(upToken.getUsername());
        if(user==null){
            return null;
        }else{
            AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
            return info;
        }

    }

}


6、修改傳統登錄爲shiro登錄

package cn.itcast.jk.action;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;

import cn.itcast.common.SysConstant;
import cn.itcast.jk.service.UserService;

/**
 * @Description: 登錄和推出類
 * @Author:     傳智播客 java學院 宋江
 * @Company:    http://java.itcast.cn
 * @CreateDate: 2014年10月31日
 */
public class LoginAction extends BaseAction {

    private static final long serialVersionUID = 1L;

    private String username;
    private String password;

    private UserService userService;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String login() throws Exception {    
        /*
         * shiro登錄方式:根據用戶名獲取密碼,密碼爲null非法用戶;有密碼檢查是否用戶填寫的密碼
         * 登錄成功後無需往httpsession中存放當前用戶,這樣就跟web容器綁定,關聯太緊密;它自己創建
         * subject對象,實現自己的session。這個跟web容器脫離,實現鬆耦合。
         */

        //調用shiro判斷當前用戶是否是系統用戶
        Subject subject = SecurityUtils.getSubject();   //得到當前用戶
        //shiro是將用戶錄入的登錄名和密碼(未加密)封裝到token對象中
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);

        try{
            subject.login(token);   //自動調用AuthRealm.doGetAuthenticationInfo

            //寫seesion,保存當前user對象
            User curUser = (User)subject.getPrincipal();            //從shiro中獲取當前用戶
            System.out.println(curUser.getDept().getDeptName());    //讓懶加載變成立即加載
            Set<Role> roles = curUser.getRoles();
            for(Role role :roles){
                Set<Module> moduless =  role.getModules();
                for(Module m :moduless)
                   System.out.println(m.getName());
            }
            session.put(SysConstant.CURRENT_USER_INFO, curUser);    //Principal 當前用戶對象
        }catch(Exception ex){
            super.put("errorInfo","用戶名密碼錯誤,請重新填寫!");
            ex.printStackTrace();

            return "login";
        }
        return SUCCESS;
    }

    public String logout(){
        session.remove(SysConstant.CURRENT_USER_INFO);      //刪除session
        return "logout";
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}



7、授權(另一種加載數據的思想   可省略因爲在登錄時已加載)
根據用戶查詢出角色對應的權限,並返回權限串

-hql,service

    public List<String> getPermission(String userName) {
        List<String> _list = new ArrayList<String>();

        //用戶,角色,權限,兩級多對多,使用left join關聯實現
        String hql = "select p from User as u left join u.roles as r left join r.modules as p where u.username='"+userName+"'";
        List<Module> moduleList = baseDao.find(hql, Module.class, null);

        for(Module m : moduleList){
            if(m!=null){    //觀察hibernate實現的SQL,會多出一條Null記錄
                _list.add(m.getName());
            }
        }

        return _list;
    }



在realm中進行授權userService.getPermission

    //授權
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        log.info("執行授權...");

        //獲取登錄用戶的權限,配合jsp頁面中的shiro標籤進行控制
        User curUser = (User) principals.fromRealm(getName()).iterator().next();  
        String userName = curUser.getUsername();
        List<String> sList = userService.getPermission(userName );
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        for(String permission : sList){
            //設置當前用戶的權限
            authorizationInfo.addStringPermission(permission);
        }

        return authorizationInfo;
    }


8、頁面使用shiro標籤,/home/title.jsp 主菜單


<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>


                        <shiro:hasPermission name="sysadmin">
                        <span id="topmenu" onclick="toModule('sysadmin');">系統管理</span>
                        </shiro:hasPermission>

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