[java][shrio]:概念+spring集成

核心概念

Subject:主體,可以看到主體可以是任何可以與應(yīng)用交互的“用戶(hù)”;
SecurityManager:相當(dāng)于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心臟;所有具體的交互都通過(guò)SecurityManager進(jìn)行控制;它管理著所有Subject、且負(fù)責(zé)進(jìn)行認(rèn)證和授權(quán)、及會(huì)話、緩存的管理。
Authenticator:認(rèn)證器,負(fù)責(zé)主體認(rèn)證的,這是一個(gè)擴(kuò)展點(diǎn),如果用戶(hù)覺(jué)得Shiro默認(rèn)的不好,可以自定義實(shí)現(xiàn);其需要認(rèn)證策略(Authentication Strategy),即什么情況下算用戶(hù)認(rèn)證通過(guò)了;
Authorizer:授權(quán)器,或者訪問(wèn)控制器,用來(lái)決定主體是否有權(quán)限進(jìn)行相應(yīng)的操作;即控制著用戶(hù)能訪問(wèn)應(yīng)用中的哪些功能;
Realm:可以有1個(gè)或多個(gè)Realm,可以認(rèn)為是安全實(shí)體數(shù)據(jù)源,即用于獲取安全實(shí)體的;可以是JDBC實(shí)現(xiàn),也可以是LDAP實(shí)現(xiàn),或者內(nèi)存實(shí)現(xiàn)等等;由用戶(hù)提供;注意:Shiro不知道你的用戶(hù)/權(quán)限存儲(chǔ)在哪及以何種格式存儲(chǔ);所以我們一般在應(yīng)用中都需要實(shí)現(xiàn)自己的Realm;
SessionManager:如果寫(xiě)過(guò)Servlet就應(yīng)該知道Session的概念,Session呢需要有人去管理它的生命周期,這個(gè)組件就是SessionManager;而Shiro并不僅僅可以用在Web環(huán)境,也可以用在如普通的JavaSE環(huán)境、EJB等環(huán)境;所有呢,Shiro就抽象了一個(gè)自己的Session來(lái)管理主體與應(yīng)用之間交互的數(shù)據(jù);可以實(shí)現(xiàn)分布式的會(huì)話管理;
SessionDAO:DAO大家都用過(guò),數(shù)據(jù)訪問(wèn)對(duì)象,用于會(huì)話的CRUD,比如我們想把Session保存到數(shù)據(jù)庫(kù),那么可以實(shí)現(xiàn)自己的SessionDAO,通過(guò)如JDBC寫(xiě)到數(shù)據(jù)庫(kù);比如想把Session放到redis中,可以實(shí)現(xiàn)自己的redis  SessionDAO;另外SessionDAO中可以使用Cache進(jìn)行緩存,以提高性能;
CacheManager:緩存控制器,來(lái)管理如用戶(hù)、角色、權(quán)限等的緩存的;因?yàn)檫@些數(shù)據(jù)基本上很少去改變,放到緩存中后可以提高訪問(wèn)的性能
Cryptography:密碼模塊,Shiro提高了一些常見(jiàn)的加密組件用于如密碼加密/解密的。

spring集成

1、導(dǎo)入相關(guān)依賴(lài)
<dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-quartz</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
2.在web.xml配置ShiroFilter
<!-- shiro過(guò)慮器,DelegatingFilterProx會(huì)從spring容器中找shiroFilter 必須放到web.xml前面-->
    <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.添加Shiro配置文件
3.1自定義Realm
<bean id="userRealm" class="com._520it.wms.realm.UserRealm"></bean>

public class UserRealm extends AuthorizingRealm {
    @Override
    public String getName() {
        return "UserRealm";
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        if(!"admin".equals(principal)){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(currentUser, currentUser.getPassword(),getName());
        return authenticationInfo;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Employee currentUser = (Employee) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<String> roles = new ArrayList<String>();
        roles.addAll(Arrays.asList("HR MGR","ORDER MGR"));
        authorizationInfo.addRoles(roles);
        List<String> perms = new ArrayList<String>();
        perms.addAll(Arrays.asList("employee:view","employee:delete"));
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }
}
3.2安全管理器SecurityManager
<!-- 配置安全管理器SecurityManager -->
在applicationContext-shrio.xml中添加如下配置:
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="userRealm"/>
</bean>
3.3Shiro的Web過(guò)濾器
注意:名字必須要和web.xml中配置的名字一致
在applicationContext-shrio.xml中添加如下配置:
<!-- 定義ShiroFilter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login.action"/>
        <property name="successUrl" value="/main.action"/>
        <property name="unauthorizedUrl" value="/nopermission.jsp"/>
        <property name="filterChainDefinitions">
            <value>
            <!-- 靜態(tài)資源不需要攔截-->
                /js/**=anon
                /images/**=anon
                /style/**=anon
                /logout.action=logout
                /**=authc
            </value>
        </property>
    </bean>
4.修改登錄方法
    public String execute()throws Exception{
        HttpServletRequest req = ServletActionContext.getRequest();
        if(SecurityUtils.getSubject().isAuthenticated()){
            return "main";
        }
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        //根據(jù)shiro返回的異常類(lèi)路徑判斷,拋出指定異常信息
        if(exceptionClassName!=null){
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                //最終會(huì)拋給異常處理器
                super.addActionError("賬號(hào)不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(
                    exceptionClassName)) {
                super.addActionError("用戶(hù)名/密碼錯(cuò)誤");
            } else {
                super.addActionError("其他異常信息");//最終在異常處理器生成未知錯(cuò)誤
            }
        }
        return "login";
    }
5.使用shiro注解授權(quán)
在applicationContext-shrio.xml中添加如下配置:   
<!-- 開(kāi)啟aop,對(duì)類(lèi)代理 -->
    <aop:config proxy-target-class="true"></aop:config>
    <!-- 開(kāi)啟shiro注解支持 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>

在需要控制的方法上貼上注解:@RequiresPermissions("employee:view")
6.緩存管理
7.會(huì)話管理
<!--會(huì)話管理-->
在applicationContext-shrio.xml中添加如下配置:
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- session的失效時(shí)長(zhǎng),單位毫秒 -->
        <property name="globalSessionTimeout" value="60000"/>
        <!-- 刪除失效的session -->
        <property name="deleteInvalidSessions" value="true"/>
</bean>

<!-- 配置安全管理器SecurityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>
8.添加憑證匹配器
在applicationContext-shrio.xml中添加如下配置:
<!--自定義realm-->
<bean id="myRealm" class="com._520it.wms.realm.MyRealm">
   <property name="employeeService" ref="employeeService"/>
   <property name="roleService" ref="roleService"/>
   <property name="permissionService" ref="permissionService"/>
   <property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!--添加憑證匹配器(為密碼加鹽操作)-->
 <bean id="credentialsMatcher"
        class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5" />
        <property name="hashIterations" value="1" />
</bean>
9.通過(guò)數(shù)據(jù)庫(kù)進(jìn)行認(rèn)證和授權(quán)

常見(jiàn)注解

@RequiresAuthentication
驗(yàn)證用戶(hù)是否登錄,等同于方法subject.isAuthenticated() 結(jié)果為true時(shí)。

@RequiresUser
驗(yàn)證用戶(hù)是否被記憶,user有兩種含義:
一種是成功登錄的(subject.isAuthenticated() 結(jié)果為true);
另外一種是被記憶的(subject.isRemembered()結(jié)果為true)。

@RequiresGuest
驗(yàn)證是否是一個(gè)guest的請(qǐng)求,與@RequiresUser完全相反。
 換言之,RequiresUser  == !RequiresGuest。
此時(shí)subject.getPrincipal() 結(jié)果為null.

@RequiresRoles
例如:
@RequiresRoles("aRoleName");
  void someMethod();
如果subject中有aRoleName角色才可以訪問(wèn)方法someMethod。如果沒(méi)有這個(gè)權(quán)限則會(huì)拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。

@RequiresPermissions
例如: 
@RequiresPermissions({"file:read", "write:aFile.txt"} )
 void someMethod();
要求subject中必須同時(shí)含有file:read和write:aFile.txt的權(quán)限才能執(zhí)行方法someMethod()。否則拋出異常[AuthorizationException](http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/AuthorizationException.html)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,687評(píng)論 18 399
  • 01 在社會(huì)上,摸爬滾打這些年,我發(fā)現(xiàn)一個(gè)現(xiàn)象:越是有本事的人越懂得控制自己的情緒,越是沒(méi)本事的人脾氣越是大。 在...
    饑者求食閱讀 366評(píng)論 9 17
  • 我是一名在線英語(yǔ)老師,每天會(huì)接觸到不同年齡階段的學(xué)生。其中最多的是孩子。孩子年齡也從三歲到十幾歲不等。因?yàn)槠浞奖阈?..
    心若顏閱讀 957評(píng)論 2 0
  • 自打參加了陽(yáng)光老師生命之舞公益行之后,對(duì)生命之舞的課程無(wú)比的期待,終于,上個(gè)周末去完成了一階的課程?,F(xiàn)在整理...
    嗯維生素閱讀 416評(píng)論 0 0

友情鏈接更多精彩內(nèi)容