apache shiro 整合 SSM框架信息

结合网上搜寻的信息、参考各个网站shiro配置,写了一套适应我们自己的系统的权限系统框架,做下记录,毕竟是新学习的一个框架系统,其中还有许多漏洞,也希望各位前辈指正其中的不足之处
第一步:
        导入 jar 到pom.xml文件
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.4.0</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-spring</artifactId>
          <version>1.4.0</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-web</artifactId>
          <version>1.4.0</version>
        </dependency>
        <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-ehcache</artifactId>
          <version>1.4.0</version>
        </dependency>

第二步:
     配置shiro信息到web.xml配置文件中,其实shiro也可以说是一个Fileter

     <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>  

第三步:
    添加spring-shiro.xml到web.xml文件中默认加载,这个需要注意的是配置在 Spring-mvc.xml 配置之后、不然的话Controller加载时找不到注解注入的Service
spring-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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc  
       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
          <property name="loginUrl" value="/goLogin.do"/> <!--登录页面 -->
             <property name="successUrl" value="/sysIndex.do"/><!--登录成功页面,如果自己设置了返回页面,则不跳转-->
          <property name="unauthorizedUrl" value="/erro.do"/> <!-- 没有权限跳转的地址 -->
        <property name="filterChainDefinitions">
            <value>
                /goLogin.do=anon <!--表示都可以访问-->
                /login.do=anon <!--表示都可以访问-->
                /logout.do=anon <!--表示都可以访问-->
                /error=authc
                /static/** = anon
                /views/include/** = anon
                <!--/home=perms[home] perms表示需要该权限才能访问的页面-->
                <!-- /admin=roles["admin"] roles["admin,user"] 只有拥有admin角色的用户才可访问,同时需要拥有多个角色的话,用引号引起来,中间用逗号隔开-->
                <!--/admin=anon-->
                /** = authc   <!-- authc表示需要认证才能访问的页面-->
            </value>    
        </property>
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="MatcherRealm"/>   
    </bean>

    <!-- 自定义Realm -->
    <bean id="MatcherRealm" class="com.cn.zx.filter.MatcherRealm">
       <!--  定义凭证匹配器 -->
        <property name="credentialsMatcher" ref="credentialsMatcher"></property> 
    </bean> 
    
    <!-- 凭证匹配器 org.apache.shiro.authc.credential.HashedCredentialsMatcher-->
    <bean id="credentialsMatcher" class="com.cn.zx.filter.MatcherPass">
         <!-- 密码加密验证方式 -->
       <property name="hashAlgorithmName" value="MD5"></property>
    </bean>
</beans>

第四步:
    自定义Realm凭证匹配器,下面是根据我自己的系统需求更改的匹配信息,其中包含两部分{
        第一部分:加入权限和角色信息到SimpleAuthorizationInfo类中
        第二部分:加入登录用户信息到SimpleAuthenticationInfo类中
    }

/**
 * 自定义凭证匹配器
 * @author Maochao-zhu
 * 
 */
public class MatcherRealm extends AuthorizingRealm {
     @Resource
     UserService userService;
     @Resource
     RoleService roleService;
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录的用户信息
        User user = (User)principalCollection.getPrimaryPrincipal();
        if(user!=null){
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            //获取用户角色、和菜单权限
            if(null!=user && null!=user.getRoleId()){
                Role  role = roleService.getRoleById(user.getRoleId());
                info.addRole(role.getId().toString());//加入角色
                //添加菜单和按钮权限、
                info = addPermission(user, info); 
            }else{
                info.addRole("-1000");//加入角色
                info.addStringPermission("-1000"); //加入权限
            }
            return info;
        }
        return null;
    }

    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        // TODO Auto-generated method stub
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //通过表单接收的用户名
        String username=token.getUsername();
        if(username!=null&&!"".equals(username)){
            User user=userService.getUserByLogin(username);
            if(user!=null){
                return new SimpleAuthenticationInfo(user,user.getPwd(),getName());
            }
        }
        System.out.println("认证失败");
        return null;
    }
    
    /**
     * 添加权限
     * @param username
     * @param info
     * @return
     */
    private SimpleAuthorizationInfo addPermission(User user,SimpleAuthorizationInfo info) {
        Role  role = roleService.getRoleById(user.getRoleId());
        if(null!=role && null!=role.getMenuControl() && !"".equals(role.getMenuControl())){
            String []menuArr=role.getMenuControl().split(",");
            //获取菜单和按钮权限、
            for(String m:menuArr){
                info.addStringPermission(m); 
            }
            //添加按钮权限
            String []operArr=role.getOperControl().split(",");
            for(String m:operArr){
                info.addStringPermission(m); 
            }
            if((menuArr ==null ||menuArr.length==0) && (operArr ==null || operArr.length==0)){
                info.addStringPermission("-1000"); 
            } 
        }else{
            info.addStringPermission("-1000"); 
        }
        return info;  
    }
}

第五步:自定义密码校验匹配器或者用默认密码匹配器
    5.1默认密码验证匹配器:
     <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
            <!-- 加密算法名称-->
            <property name="hashAlgorithmName" value="MD5"></property>
            <!-- 散列次数-->
            <property name="hashIterations" value="2"></property>
    </bean> 
    5.2 自定义密码验证匹配器:
    配置
    <bean id="credentialsMatcher" class="com.cn.zx.filter.MatcherPass">
         <!-- 密码加密验证方式 -->
       <property name="hashAlgorithmName" value="MD5"></property>
    </bean>
    自定义密码匹配器其实就是重写了默认密码匹配器的HashedCredentialsMatcher里的方法,我这里是根据我们的系统密码验证规则更改的方法:
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String) token.getPrincipal();
        UsernamePasswordToken autoken = (UsernamePasswordToken) token;
        String password= String.copyValueOf(autoken.getPassword());
        String accountCredentials = String.valueOf(getCredentials(info));
        boolean match = Md5Util.isEqualPassWord(password,accountCredentials);
        return match;
    }
    

转载于:https://my.oschina.net/u/3204029/blog/3043675

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值