zoukankan      html  css  js  c++  java
  • Shiro授权

    1.shiro授权角色、权限

    授权

    Mapper接口

      Set<String> getRolesByUserId(@Param("userid") Integer userid);
    
      Set<String>  getPersByUserId(@Param("userid") Integer userid);

     Mapper.xml

    <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
      select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
        where u.userid = ur.userid and ur.roleid = r.roleid
        and u.userid = #{userid}
    </select>
      <select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
      select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
      where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
      and u.userid = #{userid}
    </select>

    service

    public Set<String> getRolesByUserId(Integer userId);
    
    public Set<String> getPersByUserId(Integer userId);

    ShiroUserServiceImpl

    @Service("shiroUserService")
    public class ShiroUserServiceImpl implements ShiroUserService {
        @Autowired
        private ShiroUserMapper shiroUserMapper;
    
        @Override
        public Set<String> getRolesByUserId(Integer userId) {
            return shiroUserMapper.getRolesByUserId(userId);
        }
    
        @Override
        public Set<String> getPersByUserId(Integer userId) {
            return shiroUserMapper.getPersByUserId(userId);
            }
            }

     重写自定义realm中的授权方法

    /**
         * 授权
         *
         * @param principalCollection
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            String uname = principalCollection.getPrimaryPrincipal().toString();
            ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
            Set<String> perids = this.shiroUserService.getPersByUserId(shiroUser.getUserid());
            Set<String> roleIds =this.shiroUserService.getRolesByUserId(shiroUser.getUserid());
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(roleIds);
            info.setStringPermissions(perids);
    
            return info;
        }

    注解式开发

    常用注解介绍

    @RequiresAuthenthentication:表示当前Subject已经通过login进行身份验证;即 Subject.isAuthenticated()返回 true
    
      @RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的
    
      @RequiresGuest:表示当前Subject没有身份验证或者通过记住我登录过,即是游客身份
    
      @RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示当前Subject需要角色admin和user
    
      @RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示当前Subject需要权限user:delete或者user:b

     注解的使用

    @RequiresUser
        @ResponseBody
        @RequestMapping("/passUser")
        public String passUser() {
            return "身份认证成功";
        }
    @RequiresRoles(value={"1","4"},logical = Logical.OR)
        @ResponseBody
        @RequestMapping("/passRole")
        public String passRole() {
            return "角色认证成功";
        }
    @RequiresPermissions(value={"user:update","user:create"},logical = Logical.AND)
        @ResponseBody
        @RequestMapping("/passPer")
        public String passPer() {
            return "权限认证成功";
        }

    springmvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.hmc"/>
    
    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    <mvc:annotation-driven></mvc:annotation-driven>
    
    <!--3) ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
    <property name="viewClass"
    value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix" value="/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 文件最大大小(字节) 1024*1024*50=50M-->
    <property name="maxUploadSize" value="52428800"></property>
    <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
    <property name="resolveLazily" value="true"/>
    </bean>
    
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true"></property>
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
    </bean>
    
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
    <props>
    <prop key="org.apache.shiro.authz.UnauthorizedException">
    unauthorized
    </prop>
    </props>
    </property>
    <property name="defaultErrorView" value="unauthorized"/>
    </bean>
    
    <!--4) 单独处理图片、样式、js等资源 -->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    <mvc:resources location="/static/" mapping="/static/**"/>
    </beans>

    jsp页面

    <ul>
        shiro注解
        <li>
            <a href="${pageContext.request.contextPath}/passUser">用户认证</a>
        </li>
        <li>
            <a href="${pageContext.request.contextPath}/passRole">角色</a>
        </li>
        <li>
            <a href="${pageContext.request.contextPath}/passPer">权限认证</a>
        </li>
    </ul>

     Controller

    @RequiresUser
        @ResponseBody
        @RequestMapping("passUser")
        public String passUser(){
            return "用户认证访问成功!!!";
        }
        @RequiresRoles(value = {"2"} ,logical = Logical.AND)
        @ResponseBody
        @RequestMapping("passRole")
        public String passRole(){
            return "角色访问成功!!!";
        }
        @RequiresPermissions(value = {"user:update","user:load"},logical = Logical.AND)
        @ResponseBody
        @RequestMapping("passPer")
        public String passPer(){
            return "权限访问成功!!!";
        }
  • 相关阅读:
    JQuery实现页面跳转
    CSS中让背景图片居中且不平铺
    C#后台将string="23.00"转换成int类型
    BootStrap的一些基本语法
    CSS实现文字阴影的效果
    BootStrap自定义轮播图播放速度
    BootStrap 轮播插件(carousel)支持左右手势滑动的方法(三种)
    C#常用快捷键
    jQuery hover() 方法
    鼠标移动有尾巴
  • 原文地址:https://www.cnblogs.com/xmf3628/p/11800295.html
Copyright © 2011-2022 走看看