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>
相关文章
相关标签/搜索