如何在spring中整合shiro

這篇文章將為大家詳細(xì)講解有關(guān)如何在spring中整合shiro,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)建站專注于企業(yè)全網(wǎng)營(yíng)銷推廣、網(wǎng)站重做改版、伊犁網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5場(chǎng)景定制、商城系統(tǒng)網(wǎng)站開發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為伊犁等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。

一、添加相關(guān)依賴

<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-core</artifactId>
   <version>1.2.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-web</artifactId>
   <version>1.2.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-ehcache</artifactId>
   <version>1.2.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.2.1</version>
  </dependency> 
  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
  </dependency>

二、編寫代碼

1、自定義realm

public class CommonRealm extends AuthorizingRealm {
 @Autowired
 private UserLoginService userLoginService;
 @Override
 public String getName() {
  return "CommonRealm";
 }
 //授權(quán)
 @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  String usernmae = (String) principals.getPrimaryPrincipal();
  List<String> permissions = new ArrayList<String>();
  if ("admin".equals(usernmae)) {
   permissions.add("admin:ee");
  }
  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  info.addStringPermissions(permissions);
  return info;
 }
 //身份認(rèn)證
 @Override
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  String username = (String) token.getPrincipal();
  User user = userLoginService.getUser(username);
  if (user == null) {
   return null;
  }
  SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, user.getPassword(), getName());
  return info;
 }
}

2、login controller

@Controller
public class UserAction {
 @Autowired
 private UserLoginService userLoginService;
 @RequestMapping("/login.do")
 public String userLogin(HttpServletRequest request, String username, String password) throws Exception {
  // 如果登陸失敗從request中獲取異常信息,shiroLoginFailure就是shiro異常類的全限定名
  String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
  if (exceptionClassName != null) {
   if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
    // 最終會(huì)拋給異常處理器
    throw new XXXException("用戶名不存在");
   } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
    throw new XXXException("用戶名/密碼錯(cuò)誤");
   } else {
    throw new Exception();// 最終在異常處理器生成未知錯(cuò)誤
   }
  }
  // 如果登錄成功的話不走此方法,shiro認(rèn)證成功會(huì)自動(dòng)跳轉(zhuǎn)到上一個(gè)請(qǐng)求路徑,配的的successUrl沒效果,后邊會(huì)說
  // 登陸失敗走此方法,捕獲異常,然后 return ~ ,還到login頁(yè)面
  return "login.jsp";
 }
}

3、檢測(cè)權(quán)限 controller

 //此方法為了驗(yàn)證權(quán)限是否生效
 @RequestMapping("/findAll.do")
 @RequiresPermissions("admin:ee")
 public ModelAndView list(HttpServletRequest request){
  ....... 
 }

三、常見問題

因?yàn)橛幸恍┨貏e常見的問題,需要修改xml配置,所以現(xiàn)在先手問題,把xml配置放在后邊,直接就配置完善好的xml

問題一:登陸成功后shiro默認(rèn)跳到上一次請(qǐng)求,沒有上一次請(qǐng)求默認(rèn)跳到/  ,那我們就想控制調(diào)到自己定義的路徑咋辦呢?

解決方案:

步驟一:繼承FormAuthenticationFilter類,重寫onLoginSuccess方法,這里可以自定義路徑,因?yàn)檫@里自定義了成功跳轉(zhuǎn)的路徑,所以配置里的successUrl不用配置,賠了也沒效果。。

public class LoginSuccessToFilter extends FormAuthenticationFilter {
 @Override
 protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
  WebUtils.getAndClearSavedRequest(request);
  WebUtils.redirectToSavedRequest(request,response,"/findAll.do");
  return false;
 }
}

步驟二:

在shiro的xml配置文件中配置

 <bean id="myfilter" class="com.xxx.realm.LoginSuccessToFilter"></bean>

在 shiroFilter配置中引入,完整xml在后邊

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <property name="filters">
   <map>
    <entry key="authc" value-ref="myfilter"></entry>
   </map>
  </property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <property name="filters">
   <map>
    <entry key="authc" value-ref="myfilter"></entry>
   </map>
  </property>
</bean>

四、Xml配置

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:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <!-- 管理器,必須設(shè)置 -->
  <property name="securityManager" ref="securityManager"/>
  <property name="filters">
   <map>
    <entry key="authc" value-ref="myfilter"></entry>
   </map>
  </property>
  <!-- 攔截到,跳轉(zhuǎn)到的地址,通過此地址去認(rèn)證 -->
  <property name="loginUrl" value="/login.do"/>
  <!-- 認(rèn)證成功統(tǒng)一跳轉(zhuǎn)到/admin/index.do,建議不配置,shiro認(rèn)證成功自動(dòng)到上一個(gè)請(qǐng)求路徑 -->
  <!--<property name="successUrl" value="/findAll.do"/>-->
  <!-- 通過unauthorizedUrl指定沒有權(quán)限操作時(shí)跳轉(zhuǎn)頁(yè)面 -->
  <property name="unauthorizedUrl" value="/refuse.jsp"/>
  <!-- 自定義filter,可用來更改默認(rèn)的表單名稱配置 -->
  <!--<property name="filters">-->
  <!--<map>-->
  <!--&lt;!&ndash; 將自定義 的FormAuthenticationFilter注入shiroFilter中 &ndash;&gt;-->
  <!--<entry key="authc" value-ref="formAuthenticationFilter" />-->
  <!--</map>-->
  <!--</property>-->
  <property name="filterChainDefinitions">
   <value>
    <!-- 對(duì)靜態(tài)資源設(shè)置匿名訪問 -->
    /image/** = anon
    /css/** = anon
    /js/** = anon
    /logout.do = logout
    /** = authc
   </value>
  </property>
 </bean>
 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
 <!-- securityManager安全管理器 -->
 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  <property name="realm" ref="customRealm"/>
  <!-- 注入緩存管理器 -->
  <!--<property name="cacheManager" ref="cacheManager" />-->
  <!-- 注入session管理器 -->
  <!-- <property name="sessionManager" ref="sessionManager" /> -->
  <!-- 記住我 -->
  <!--<property name="rememberMeManager" ref="rememberMeManager" />-->
 </bean>
 <!-- 自定義realm -->
 <bean id="customRealm" class="com.dhl.realm.CommonRealm"></bean>
 <bean id="myfilter" class="com.dhl.realm.LoginSuccessToFilter"></bean>
 <!-- 憑證匹配器 -->
 <!--<bean id="credentialsMatcher"-->
   <!--class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">-->
  <!--&lt;!&ndash; 選用MD5散列算法 &ndash;&gt;-->
  <!--<property name="hashAlgorithmName" value="md5"/>-->
  <!--&lt;!&ndash; 進(jìn)行一次加密 &ndash;&gt;-->
  <!--<property name="hashIterations" value="1"/>-->
 <!--</bean>-->
</beans>

springmvc的配置

<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  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
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
 <context:component-scan base-package="com.dhl.controller"></context:component-scan>
 <mvc:annotation-driven></mvc:annotation-driven>
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
 <!-- 開啟shiro注解的配置移動(dòng)到這兒 -->
 <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>

關(guān)于如何在spring中整合shiro就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

分享名稱:如何在spring中整合shiro
鏈接URL:http://bm7419.com/article22/geehcc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、微信小程序、小程序開發(fā)響應(yīng)式網(wǎng)站、網(wǎng)站營(yíng)銷面包屑導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)