shiro之 shiro整合ssm


1. 整合ssm並且實現用戶登錄和菜單權限。

2. 將shiro整合到ssm中

  a).添加shiro相關jar包

  b).在web.xml種添加shiro的配置

<!-- 配置shirofilter 通過代理來配置,對象由spring容器來創建的,但是交由servlet容器來管理 -->
 <filter>
     <filter-name>shiroFilter</filter-name>
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
     <init-param>
         <!-- 表示bean的生命周期有servlet來管理 -->
         <param-name>targetFilterLifecycle</param-name>
         <param-value>true</param-value>
     </init-param>
     <init-param>
         <!--表示在spring容器中bean的id,如果不配置該屬性,那么默認和該filter的name一致-->
         <param-name>targetBeanName</param-name>
         <param-value>shiroFilter</param-value>
     </init-param>
 </filter>
 <filter-mapping>
     <filter-name>shiroFilter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>

  c)在src下添加 applicationContext-shiro.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
      <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
          <!-- 配置securityManager -->
          <property name="securityManager" ref="securityManager"/>
          <!-- 當訪問需要認證的資源時,如果沒有認證,那么將自動跳轉到該url;
              如果不配置該屬性 默認情況下會到根路徑下的login.jsp -->
          <property name="loginUrl" value="/login"></property>
          <!-- 配置認證成功后 跳轉到那個url上,通常不設置,如果不設置,那么默認認證成功后跳轉上上一個url -->
          <property name="successUrl" value="/index"></property>
          <!-- 配置用戶沒有權限訪問資源時 跳轉的頁面 -->
          <property name="unauthorizedUrl" value="/refuse"/>
          <!-- 配置shiro的過濾器鏈 -->
          <property name="filterChainDefinitions">
              <value>
                  /toLogin=anon
                  /login=authc
                  /logout=logout
                  /**=authc
              </value>
          </property>
      </bean>
      <!-- 配置securityManager -->
      <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
          <property name="realm" ref="userRealm"/>
      </bean>
      <bean id="userRealm" class="cn.wh.realm.UserRealm"/>
</beans>

d) 修改loginController中登陸方法

//登錄
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request){
        ModelAndView mv=new ModelAndView("login");
        String className=(String)request.getAttribute("shiroLoginFailure");
        if(UnknownAccountException.class.getName().equals(className)){
            //拋出自定義異常
            mv.addObject("msg", "用戶名或密碼錯誤!!");
        }else if(IncorrectCredentialsException.class.getName().equals(className)){
            //拋出自定義異常
            mv.addObject("msg", "用戶名或密碼錯誤!!");
        }else{
            mv.addObject("msg", "系統異常!!");
        }
        return mv;
    }

e) 添加自定義Realm:UserRealm

public class UserRealm extends AuthorizingRealm{
    @Override
    public String getName() {
        return "userRealm";
    }
    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        String pwd ="1111";
        return new SimpleAuthenticationInfo(username, pwd,getName());
    }
    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }
}

f)修改UserRealm實現身份認證

public class UserRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public String getName() {
        return "userRealm";
    }
    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        User user = userService.findUserByName(username);
        //設置該user的菜單
        if(user!=null){
            user.setMenus(permissionService.findByUserId(user.getId()));
        }
        return new SimpleAuthenticationInfo(user, user.getPwd(),getName());
    }
    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        
        return null;
    }
}

e)憑證匹配器配置

<!-- 配置自定義realm -->
      <bean id="userRealm" class="cn.sxt.realm.UserRealm">
          <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="2"/>
      </bean>

userRealm要相應改變

//認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        User user = userService.findUserByName(username);
        //設置該user的菜單
        if(user!=null){
            user.setMenus(permissionService.findByUserId(user.getId()));
        }
        return new SimpleAuthenticationInfo(user, user.getPwd(),ByteSource.Util.bytes(user.getSalt()),getName());
    }

logout配置,默認退出后跳轉到跟路徑下,如果需要改變則需從新配置logout過濾器,過濾器bean的id不能改變,只能為logout

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
          <!-- 配置securityManager -->
          <property name="securityManager" ref="securityManager"/>
          <!-- 當訪問需要認證的資源時,如果沒有認證,那么將自動跳轉到該url;
              如果不配置該屬性 默認情況下會到根路徑下的login.jsp -->
          <property name="loginUrl" value="/login"></property>
          <!-- 配置認證成功后 跳轉到那個url上,通常不設置,如果不設置,那么默認認證成功后跳轉上上一個url -->
          <property name="successUrl" value="/index"></property>
          <!-- 配置用戶沒有權限訪問資源時 跳轉的頁面 -->
          <property name="unauthorizedUrl" value="/refuse"/>
          <!-- 配置shiro的過濾器鏈 
              logout默認退出后跳轉到根路徑下,可以從新指定
          -->
          <property name="filterChainDefinitions">
              <value>
                  /toLogin=anon
                  /login=authc
                  /logout=logout
                  /js/**=anon
                  /css/**=anon
                  /images/**=anon
                  /**=anon
              </value>
          </property>
      </bean>
      <!-- 配置logout過濾器 -->
      <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
          <property name="redirectUrl" value="/toLogin"/>
      </bean>

改變登陸時的表單域名稱,需要從新配置authc過濾器

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
          <!-- 配置securityManager -->
          <property name="securityManager" ref="securityManager"/>
          <!-- 當訪問需要認證的資源時,如果沒有認證,那么將自動跳轉到該url;
              如果不配置該屬性 默認情況下會到根路徑下的login.jsp -->
          <property name="loginUrl" value="/login"></property>
          <!-- 配置認證成功后 跳轉到那個url上,通常不設置,如果不設置,那么默認認證成功后跳轉上上一個url -->
          <property name="successUrl" value="/index"></property>
          <!-- 配置用戶沒有權限訪問資源時 跳轉的頁面 -->
          <property name="unauthorizedUrl" value="/refuse"/>
          <!-- 配置shiro的過濾器鏈 
              logout默認退出后跳轉到根路徑下,可以從新指定
          -->
          <property name="filterChainDefinitions">
              <value>
                  /toLogin=anon
                  /login=authc
                  /logout=logout
                  /js/**=anon
                  /css/**=anon
                  /images/**=anon
                  /**=anon
              </value>
          </property>
      </bean>
      <!-- 配置authc過濾器 -->
      <bean id="authc" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
          <property name="usernameParam" value="name"/>
          <property name="passwordParam" value="pwd"/>
      </bean>

登陸頁面的改變:

<form id="slick-login" action="login" method="post">
<label for="username">username</label><input type="text" name="name" class="placeholder" placeholder="用戶名">
<label for="password">password</label><input type="password" name="pwd" class="placeholder" placeholder="密碼">
<input type="submit" value="Log In">
</form>

 

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM