首页 > 代码库 > erp12---shiro框架使用

erp12---shiro框架使用

一、知识点:

1、认证:用户身份识别,常被称为用户登录,判断用户是否登录,如果未登录则拦截其请求;
授权:访问控制,当用户登录之后,判断其身份是否有权限访问相应的资源,如果没有权限则拦截

2、
认证:
anon--不认证也可以访问
authc--必须认证才可以访问
authcBasic,user

授权:
perms--指定资源需要哪些权限才可以访问
roles,sll,rest,port
authentication    --认证
authorization    --授权
技术分享
 authentication    认证
authorization    授权

二、erp整合shiro

1、pom.xml依赖

  1. <!-- shiro -->
  2. <!-- apache shiro dependencies -->
  3. <dependency>
  4. <groupId>org.apache.shiro</groupId>
  5. <artifactId>shiro-core</artifactId>
  6. <version>${shiro.version}</version>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.apache.shiro</groupId>
  10. <artifactId>shiro-web</artifactId>
  11. <version>${shiro.version}</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.apache.shiro</groupId>
  15. <artifactId>shiro-spring</artifactId>
  16. <version>${shiro.version}</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.apache.shiro</groupId>
  20. <artifactId>shiro-aspectj</artifactId>
  21. <version>${shiro.version}</version>
  22. </dependency>

2、web.xml配置shiro过滤器

配置在struts过滤器前面
  1. <filter>
  2. <filter-name>shiroFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>shiroFilter</filter-name>
  7. <url-pattern>*.action</url-pattern>
  8. <url-pattern>*.html</url-pattern>
  9. <url-pattern>*</url-pattern>
  10. </filter-mapping>
或者urlpattern直接:<url-pattern>/*</url-pattern>

3、添加spring配置文件

applicationContext_shiro.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- shiro框架的中央枢纽 -->
  7. <property name="securityManager" ref="securityManager" />

  8. <!-- 如果访问页面或请求是没有当前登录人,会跳转到login.html中 -->
  9. <property name="loginUrl" value="/login.html" />

  10.     <!-- 如果当前登录人访问的页面或请求没有权限时,跳转到error.html -->
  11. <property name="unauthorizedUrl" value="/error.html" />

  12. <property name="filterChainDefinitions">
  13. <value>
  14. /error.html = anon
  15. /*.html = authc
  16. </value>
  17. </property>

  18. </bean>
            <!-- shiro框架的中央枢纽 -->
  1. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  2. </bean>
  3. </beans>
其中bean对象的id要和web.xml里面的过滤器的名字要一样(shiroFilter)


三、认证:

1、用shiro框架改造登录方法:


        //1、获取令牌
        Md5Hash md5 = new Md5Hash(pwdusername, 2);
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5.toString());  
        //2、获取主题
        Subject subject = SecurityUtils.getSubject();
        
        //3、开始认证
        try {
            subject.login(token);
            write(ajaxReturn(true"登陆成功"));
        } catch (AuthenticationException e) {
            write(ajaxReturn(false"登录失败,请重新登录"));
            e.printStackTrace();
        }
          

2、创建一个AuthorizingRealm的子类


        private IEmpBiz empBiz;
    public void setEmpBiz(IEmpBiz empBiz) {
        this.empBiz = empBiz;
    }
    
    /**
     * 认证
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)arg0;
        String username = token.getUsername();
        String pwd=new String(token.getPassword());
        Emp emp = empBiz.findEmpByUsernameAndPwd(usernamepwd);
        if (emp!=null) {
            //参数一: 主角    参数二:密码    参数三:realName  
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(emppwd,getName());//已经放到了session中
            return info;
        }
        
        return null;//如果这里return 的是null,loginAction中的checkUser里就会抛异常
    }  

3、配置ApplicationContext_shiro.xml添加如下代码


  1.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  2. <property name="realm" ref="erpRealm" ></property>
  3. </bean>
  4. <bean id="erpRealm" class="cn.itcast.erp.realm.ErpRealm" >
  5. <property name="empBiz" ref="empBiz" ></property>
  6. </bean>
将数据源和登录代码连接在一起

4、shiro的session管理

        取数据:
               Subject subject = SecurityUtils.getSubject();
        Emp emp = (Emp) subject.getPrincipal();  

                销毁session数据:

        Subject subject = SecurityUtils.getSubject();
        subject.logout();  

四、授权

1、完整的配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 当实例化一个bean是,spring保证该Bean所依赖的其他bean已经初始化 -->
  7. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" depends-on="myPermsFilter">
  8. <!-- shiro框架的中央枢纽 -->
  9. <property name="securityManager" ref="securityManager" />
  10. <!-- 如果访问页面或请求是没有当前登录人,会跳转到login.html中 -->
  11. <property name="loginUrl" value="/login.html" />
  12. <!-- 如果当前登录人访问的页面或请求没有权限时,跳转到error.html -->
  13. <property name="unauthorizedUrl" value="/error.html" />
  14. <property name="filters">
  15. <map>
  16. <entry key="perms" value-ref="myPermsFilter"></entry>
  17. </map>
  18. </property>
  19. <property name="filterChainDefinitions">
  20. <value>
  21. /error.html = anon
  22. /login_*.action=anon
  23. /emp_updatePwd.action= perms[]
  24. /pwd.html=perms["重置密码"]
  25. /emp_updatePwd_reset.action=perms["重置密码"]
  26. /orders.html= perms["采购申请","采购订单查询","采购审核","采购确认","采购入库","销售订单录入","销售订单查询","销售订单出库"]
  27. /orders_add.action= perms["采购申请","销售订单录入"]
  28. /goods_list.action= perms["采购申请","销售订单录入","库存查询","库存变动记录"]
  29. /supplier_list.action= perms["采购申请","销售订单录入"]
  30. /orders_listByPage.action= perms["采购申请","采购订单查询","采购审核","采购确认","采购入库","销售订单录入","销售订单查询","销售订单出库"]
  31. /orders_doCheck.action=perms["采购审核"]
  32. /orders_doStart.action=perms["采购确认"]
  33. /store_mylist.action= perms["采购入库","销售订单出库"]
  34. /orderdetail_doInstore.action=perms["采购入库"]
  35. /orderdetail_doOutstore.action=perms["销售订单出库"]
  36. /storedetail.html= perms["库存查询"]
  37. /store_*.action= perms["仓库"]
  38. /goods_get.action= perms["库存查询","库存变动记录"]
  39. /store_list.action= perms["库存查询","库存变动记录"]
  40. /store_get.action= perms["库存查询","库存变动记录"]
  41. /storedetail_listByPage.action= perms["库存查询"]
  42. /storeoper_listByPage.action= perms["库存查询"]
  43. /storeoper.html= perms["库存变动记录"]
  44. /storeoper_listByPage.action= perms["库存变动记录"]
  45. /emp_list.action= perms["库存变动记录"]
  46. /emp_get.action= perms["库存变动记录"]
  47. /store.html= perms["仓库"]
  48. /orderReport.html= perms["销售统计表"]
  49. /report_orderReport*.action= perms["销售统计表"]
  50. /orderTrend.html= perms["销售趋势分析"]
  51. /report_orderTrend*.action= perms["销售趋势分析"]
  52. /roleMenuSet.html=perms["角色权限设置"]
  53. /role_list.action=perms["角色权限设置"]
  54. /role_readRoleMenus.action=perms["角色权限设置"]
  55. /role_updateRoleMenus.action=perms["角色权限设置"]
  56. /empRoleSet.html=perms["用户角色设置"]
  57. /emp_list.action=perms["用户角色设置"]
  58. /emp_readEmpRoles.action=perms["用户角色设置"]
  59. /emp_updateEmpRoles.action=perms["用户角色设置"]
  60. /role.html= perms["角色设置"]
  61. /role_*.action= perms["角色设置"]
  62. /goodstype.html= perms["商品类型"]
  63. /goodstype_*.action= perms["商品类型"]
  64. /goods.html= perms["商品"]
  65. /goods_*.action= perms["商品"]
  66. /supplier.html = perms["供应商","客户"]
  67. /supplier_*.action = perms["供应商","客户"]
  68. /emp.html= perms["员工"]
  69. /emp_*.action= perms["员工"]
  70. /dep_list.action=perms["员工"]
  71. /dep.html= perms["部门"]
  72. /dep_*.action= perms["部门"]
  73. </value>
  74. </property>
  75. </bean>
  76. <!-- shiro框架的中央枢纽 -->
  77. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  78. <property name="realm" ref="erpRealm"></property>
  79. </bean>
  80. <bean id="erpRealm" class="cn.itcast.erp.realm.ErpRealm">
  81. <property name="empBiz" ref="empBiz"></property>
  82. <property name="menuBiz" ref="menuBiz"></property>
  83. </bean>
  84. <bean id="myPermsFilter" class="cn.itcast.erp.filter.MyPermsFilter">
  85. </bean>
  86. </beans>

2、授权代码:

  1. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  2. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  3. Emp emp = (Emp) principals.getPrimaryPrincipal();
  4. List<Menu> list = menuBiz.getMenuListByEmpuuid(emp.getUuid());
  5. for (Menu menu : list) {
  6. info.addStringPermission("部门");
  7. }
  8. return info;
  9. }

3、自定义过滤器

  1. package cn.itcast.myerp.filter;
  2. import javax.servlet.ServletRequest;
  3. import javax.servlet.ServletResponse;
  4. import org.apache.shiro.subject.Subject;
  5. import org.apache.shiro.web.filter.authz.AuthorizationFilter;
  6. public class myPermsFilter extends AuthorizationFilter {
  7. @Override
  8. protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
  9. throws Exception {
  10. Subject subject = getSubject(request, response);
  11. String [] perms=(String[]) mappedValue;
  12. if (perms!=null&&perms.length>0) {
  13. for(int i=0;i<perms.length;i++){
  14. if (subject.isPermitted(perms[i])) {
  15. return true;
  16. }
  17. }
  18. return false;
  19. }else {
  20. return false;
  21. }
  22. }
  23. }

4、增加配置文件的配置


1、
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" depends-on="myPermsFilter">
<!-- 加了depends-on="myPermsFilter" -->

2、
<property name="filters">
<map>
 <entry key="perms" value-ref="myPermsFilter"></entry>
</map>
</property>

3、
<bean id="myPermsFilter" class="cn.itcast.erp.filter.MyPermsFilter">
</bean>






































null


erp12---shiro框架使用