shiro之 shiro整合ssm

1. 整合ssm而且實現用戶登陸和菜單權限。css

2. 將shiro整合到ssm中web

  a).添加shiro相關jar包spring

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

<!-- 配置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.xmlapp

<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中登錄方法jsp

//登陸
    @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:UserRealmide

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實現身份認證post

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)憑證匹配器配置url

<!-- 配置自定義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要相應改變spa

//認證
    @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>
相關文章
相關標籤/搜索