Shiro與springmvc框架整合模擬web開發(fā)

因?yàn)槭悄M測(cè)試,就不需要數(shù)據(jù)操作層了,直接模擬緩存實(shí)現(xiàn)即可.首先 導(dǎo)包, 我這用的是maven構(gòu)建的項(xiàng)目:

<properties>  <!-- jar包版本 -->
<spring.version>4.2.5.RELEASE</spring.version>          

<shiro.version>1.2.3</shiro.version>
<junit.version>4.11</junit.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<!-- spring -->
<dependency>
   <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
 <groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>

web.xml文件配置

<!-- 字體格式 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
</init-param>
 </filter>
 <filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring事件監(jiān)聽器 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-shiro.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 <!-- springmvc -->
<!-- 配置springmvc servlet -->
<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>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- shiro -->
<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>

spring-mvc.xml配置文件

<!--自動(dòng)掃描--> 
<context:component-scan  base-package="com.floder.controller">    </context:component-scan><!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
</beans>

spring-shrio配置文件

<!-- shiroFilter工廠 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!-- 構(gòu)建securityManager環(huán)境 -->
    <property name="securityManager" ref="securityManager" />
    <!-- 用戶沒有認(rèn)證通過返回的地址 -->
    <property name="loginUrl" value="/login.action" />
    <!-- 攔截成功地址 -->
    <property name="successUrl" value="/index.action" />
    <!-- 沒有權(quán)限返回的地址 (拒絕訪問路徑)-->
    <property name="unauthorizedUrl" value="/refused.action" />
    <property name="filterChainDefinitions">
        <value>
            /index.action=authc
            /logout.action=logout
            /manager.action=perms[user:query]
        </value>
    </property>
</bean>
<!-- securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!--調(diào)用自定義realm -->
    <property name="realm" ref="myRealm" />
</bean>
<bean id="myRealm" class="com.floder.shiro.MyRealm"></bean>

配置文件有些東西還要解釋,再后面邊實(shí)踐邊解釋吧!
開始測(cè)試,由于我們直接模擬登陸,所以直接寫一個(gè)login.jsp測(cè)試,里面就一個(gè)form表單,

<h3>Shiro驗(yàn)證登陸</h3>
<form id="form" action="/login.action" method="post">
  <input type="text" name="username" />${error }<br/>                       <input type="password" name="password" /><br/>
<button type="submit" name="button">登陸</button>
</form>

再來回顧一下shiro驗(yàn)證流程,先subject.login(),再securityManager.login(),再交由Authenticator調(diào)用realm獲取驗(yàn)證信息驗(yàn)證.但這些流程在web引用中是怎么實(shí)現(xiàn)的呢?
  我們前面提到,用戶登錄的信息會(huì)儲(chǔ)存在UsernamePasswordToken中,又因?yàn)槲覀冊(cè)趙eb.xml文件中配置了Shiro攔截所有請(qǐng)求"/*",所以用戶登錄信息會(huì)儲(chǔ)存在token里面,發(fā)起登陸請(qǐng)求會(huì)調(diào)用realm驗(yàn)證信息,成功則進(jìn)入登陸成功頁面(此處是index.jsp).realm部分的代碼如下:

//授權(quán)方法
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String userId = (String) principals.getPrimaryPrincipal();
    List<String> permission = new ArrayList<String>();
            //模擬從數(shù)據(jù)庫中取得的權(quán)限信息
    permission.add("user:query");
    permission.add("user:update");
    permission.add("user:commit");
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.addStringPermissions(permission);
    return info;
}
//認(rèn)證方法
@Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userId= (String) token.getPrincipal();
System.out.println(userId);
//模擬從數(shù)據(jù)庫取得的信息
String password="floder";
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userId,password, getName());
return info;
}`

controller方法:

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(String username, String password,HttpServletRequest request){       
    Subject user = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try {
        user.login(token);
    }catch (AuthenticationException e) {
        token.clear();
        request.setAttribute("error", "用戶或密碼不正確!");
        return "/login";
    }
//這里可以多加幾個(gè)catch異常,密碼或賬號(hào)為空等等..
//這里一定需要方法重定向,否則刷新又回到登陸頁面了
    return "redirect:index.action";
}

根據(jù)這個(gè)realm我們可知只需隨便給個(gè)名字就可以,但密碼不能錯(cuò).這是模擬就不要在意太多了.
如果成功就能進(jìn)入登陸成功頁面了,但我們沒有實(shí)現(xiàn)攔截.所以我們需要配置攔截地址,就有要回到我們的xml配置了,在spring-shiro.xml中shiroFilter里面的filterChainDefinitions屬性配置過濾器,語法規(guī)則如下:
過濾器定義 格式:(意義 :內(nèi)置過濾器)

    anon(匿名)  org.apache.shiro.web.filter.authc.AnonymousFilter
    authc(身份驗(yàn)證)       org.apache.shiro.web.filter.authc.FormAuthenticationFilter
    authcBasic(http基本驗(yàn)證)    org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
    logout(退出)        org.apache.shiro.web.filter.authc.LogoutFilter
    noSessionCreation(不創(chuàng)建session) org.apache.shiro.web.filter.session.NoSessionCreationFilter
    perms(許可驗(yàn)證)  org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
    port(端口驗(yàn)證)   org.apache.shiro.web.filter.authz.PortFilter
    rest  (rest方面)  org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
    roles(權(quán)限驗(yàn)證)  org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
    ssl (ssl方面)   org.apache.shiro.web.filter.authz.SslFilter
    user (用戶方面)  org.apache.shiro.web.filter.authc.UserFilter

接下來只需在我們的登陸成功地址(index.action)前加上過濾器就行了: /index.action=authc
同理,登出的話只需配置一個(gè)請(qǐng)求(無所謂controller中有沒有對(duì)應(yīng)的地址處理)即可,然后再加一個(gè)logout:/logout.action=logout

現(xiàn)在來看授權(quán)部分:Shiro一共有三種方法給Subject授權(quán)(這里講javaee方面,javase前面的測(cè)試方法里面已經(jīng)有了)
①.過濾器配置 /請(qǐng)求地址=perms[權(quán)限名(多個(gè)需用引號(hào)標(biāo)識(shí))]
②.基于注解配置 這里我們是在controller層配置呢還是在service層配置呢?肯定是在controller層,因?yàn)閟ervice里面有可能這個(gè)方法需要多次重用,但不一定都需要這個(gè)權(quán)限.知道了地方直接加就可以了,
@RequiresPermissions("權(quán)限名")
就這樣還不行,因?yàn)闆]有告訴springmvc這是Shiro的注解,所以還需要在spring-mvc.xml文件中加兩行配置

<!-- 開啟aop對(duì)類代理 -->
<aop:config proxy-target-class="true"></aop:config>
<!-- 開啟對(duì)shiro注解的支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

命名空間就不說了,但就這樣使用jtetty測(cè)試時(shí)會(huì)報(bào)錯(cuò):沒有acpect這里面的某個(gè)類,還需在pom文件中加上

<!-- aop代理 -->
    <dependency>
        <groupId>asm</groupId>
        <artifactId>asm</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version> 1.6.11</version>
    </dependency>

加上了,然后就可以測(cè)試權(quán)限了.
③基于jsp標(biāo)簽的配置,這個(gè)首先要在jsp種導(dǎo)入標(biāo)簽庫
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
prefix屬性隨你填,但要和所使用的相同
<shiro:hasPermission name=""></shiro:hasPermission>
這樣,三種方法都講完了,可以開始測(cè)試了(最好一個(gè)一個(gè)測(cè)試);
  講到這里,Shiro你已經(jīng)會(huì)用很多實(shí)用功能了,但是原理部分還是有點(diǎn)問題:比如我前面的注冊(cè)表單input的name名字可不可以改,我為什么一定是username和password?如果我要加驗(yàn)證碼怎么處理?如果系統(tǒng)被入侵來了個(gè)陌生人,我們發(fā)現(xiàn)了,想要改變他的權(quán)限怎么做?還有,怎么設(shè)置session的時(shí)間限制?等等 其實(shí)這些都有辦法解決,只要你知道原理,其實(shí)Shiro進(jìn)行表單驗(yàn)證是通過FormAuthenticationFilter這個(gè)類來實(shí)現(xiàn)的,部分源碼:

shiro-FormAuthentication.jpg

里面有三個(gè)常量已近被定死了,當(dāng)然也可以自己配置,那就需要自己自定義配置這個(gè)bean了,給他設(shè)置兩個(gè)屬性名為usernameParam和passwordParam,屬性就是表單的name屬性值.那么驗(yàn)證碼也用的這個(gè)原理,自定義一個(gè)類繼承FormAuthenticationFilter這個(gè)類的 onAccessDenied方法,然后從域中取值比較即可,就不演示了.
  第二個(gè)問題,如果發(fā)現(xiàn)陌生人入侵系統(tǒng),怎么及時(shí)修改權(quán)限呢?只需在Controllor層發(fā)送一個(gè)ajax請(qǐng)求處理某個(gè)方法就行了,方法內(nèi)部代碼實(shí)現(xiàn):
getAuthenticationCache().clear()

設(shè)置session失效時(shí)間?根據(jù)Shiro內(nèi)部架構(gòu)可知只需在securityManager里面設(shè)置這個(gè)屬性:
<property name="globalSessionTimeout" value="1800000"/>

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,537評(píng)論 19 139
  • 一、架構(gòu) 要學(xué)習(xí)如何使用Shiro必須先從它的架構(gòu)談起,作為一款安全框架Shiro的設(shè)計(jì)相當(dāng)精妙。Shiro的應(yīng)用...
    ITsupuerlady閱讀 3,617評(píng)論 4 32
  • Apache Shiro Apache Shiro 是一個(gè)強(qiáng)大而靈活的開源安全框架,它干凈利落地處理身份認(rèn)證,授權(quán)...
    羅志贇閱讀 3,329評(píng)論 1 49
  • 學(xué)習(xí)任務(wù)目標(biāo) 用戶必須要登陸之后才能訪問定義鏈接,否則跳轉(zhuǎn)到登錄頁面。 對(duì)鏈接進(jìn)行權(quán)限控制,只有當(dāng)當(dāng)前登錄用戶有這...
    z77z閱讀 71,429評(píng)論 39 274
  • “在一個(gè)葬禮上,大部分人寧愿做躺在棺材里的那個(gè)人,也不愿意站在所有人面前致悼詞?!?這是我聽到過的,描述人們對(duì)演講...
    e17169820574閱讀 686評(píng)論 8 14

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