• Shiro授权


    一、shiro授权角色、权限

    在这里插入图片描述

    1、UserMapper.java

    package com.xnx.ssm.mapper;
    
    import com.xnx.ssm.model.User;
    import org.springframework.stereotype.Repository;
    
    import java.util.Set;
    
    @Repository
    public interface UserMapper {
        int deleteByPrimaryKey(Integer userid);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer userid);
    
        User queryByName(String userName);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    
        Set<String> getRolesByUserId(String userName);
    
        Set<String> getPersByUserId(String userName);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    2、UserMapper.xml

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.xnx.ssm.mapper.UserMapper" >
      <resultMap id="BaseResultMap" type="com.xnx.ssm.model.User" >
        <constructor >
          <idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
          <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
          <arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
        constructor>
      resultMap>
      <sql id="Base_Column_List" >
        userid, username, password, salt, createdate
      sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from t_shiro_user
        where userid = #{userid,jdbcType=INTEGER}
      select>
      <select id="queryByName" resultType="com.xnx.ssm.model.User" parameterType="java.lang.String">
        select
        <include refid="Base_Column_List" />
        from t_shiro_user
        where userName = #{userName}
      select>
    
      <select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.String">
      select ur.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.username = #{username}
      select>
      <select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.String">
      select rp.perid 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.username = #{username}
      select>
    
    
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from t_shiro_user
        where userid = #{userid,jdbcType=INTEGER}
      delete>
      <insert id="insert" parameterType="com.xnx.ssm.model.User" >
        insert into t_shiro_user (userid, username, password, 
          salt, createdate)
        values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
      insert>
      <insert id="insertSelective" parameterType="com.xnx.ssm.model.User" >
        insert into t_shiro_user
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="userid != null" >
            userid,
          if>
          <if test="username != null" >
            username,
          if>
          <if test="password != null" >
            password,
          if>
          <if test="salt != null" >
            salt,
          if>
          <if test="createdate != null" >
            createdate,
          if>
        trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="userid != null" >
            #{userid,jdbcType=INTEGER},
          if>
          <if test="username != null" >
            #{username,jdbcType=VARCHAR},
          if>
          <if test="password != null" >
            #{password,jdbcType=VARCHAR},
          if>
          <if test="salt != null" >
            #{salt,jdbcType=VARCHAR},
          if>
          <if test="createdate != null" >
            #{createdate,jdbcType=TIMESTAMP},
          if>
        trim>
      insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.xnx.ssm.model.User" >
        update t_shiro_user
        <set >
          <if test="username != null" >
            username = #{username,jdbcType=VARCHAR},
          if>
          <if test="password != null" >
            password = #{password,jdbcType=VARCHAR},
          if>
          <if test="salt != null" >
            salt = #{salt,jdbcType=VARCHAR},
          if>
          <if test="createdate != null" >
            createdate = #{createdate,jdbcType=TIMESTAMP},
          if>
        set>
        where userid = #{userid,jdbcType=INTEGER}
      update>
      <update id="updateByPrimaryKey" parameterType="com.xnx.ssm.model.User" >
        update t_shiro_user
        set username = #{username,jdbcType=VARCHAR},
          password = #{password,jdbcType=VARCHAR},
          salt = #{salt,jdbcType=VARCHAR},
          createdate = #{createdate,jdbcType=TIMESTAMP}
        where userid = #{userid,jdbcType=INTEGER}
      update>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114

    3、UserBiz

    package com.xnx.ssm.biz;
    
    import com.xnx.ssm.model.User;
    
    import java.util.Set;
    
    /**
     * @author xnx
     * @create 2022-08-25 18:06
     */
    public interface UserBiz {
        int deleteByPrimaryKey(Integer userid);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer userid);
    
        User queryByName(String userName);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    
        Set<String> getRolesByUserId(String userName);
    
        Set<String> getPersByUserId(String userName);
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    4、UserBizImpl

    package com.xnx.ssm.biz.impl;
    
    import com.xnx.ssm.biz.UserBiz;
    import com.xnx.ssm.mapper.UserMapper;
    import com.xnx.ssm.model.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Set;
    
    /**
     * @author xnx
     * @create 2022-08-25 18:08
     */
    @Service("UserService")
    public class UserBizImpl implements UserBiz {
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public int deleteByPrimaryKey(Integer userid) {
            return userMapper.deleteByPrimaryKey(userid);
        }
    
        @Override
        public int insert(User record) {
            return userMapper.insert(record);
        }
    
        @Override
        public int insertSelective(User record) {
            return userMapper.insertSelective(record);
        }
    
        @Override
        public User selectByPrimaryKey(Integer userid) {
            return userMapper.selectByPrimaryKey(userid);
        }
    
        @Override
        public User queryByName(String userName) {
            return userMapper.queryByName(userName);
        }
    
        @Override
        public int updateByPrimaryKeySelective(User record) {
            return userMapper.updateByPrimaryKeySelective(record);
        }
    
        @Override
        public int updateByPrimaryKey(User record) {
            return userMapper.updateByPrimaryKey(record);
        }
    
        @Override
        public Set<String> getRolesByUserId(String userName) {
            return userMapper.getRolesByUserId(userName);
        }
    
        @Override
        public Set<String> getPersByUserId(String userName) {
            return userMapper.getPersByUserId(userName);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    5、applicationContext-shiro.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           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">
    
        
        <bean id="shiroRealm" class="com.xnx.ssm.shiro.Myrealm">
            <property name="userBiz" ref="UserService" />
            
            
            
            
            <property name="credentialsMatcher">
                <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                    
                    <property name="hashAlgorithmName" value="md5"/>
                    
                    <property name="hashIterations" value="1024"/>
                    
                    <property name="storedCredentialsHexEncoded" value="true"/>
                bean>
            property>
        bean>
    
        
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realm" ref="shiroRealm" />
        bean>
    
        
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            
            <property name="securityManager" ref="securityManager" />
            
            <property name="loginUrl" value="/login"/>
            
            
            
            <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
            
            <property name="filterChainDefinitions">
                <value>
                    
                    
                    
                    
                    /user/login=anon
                    /user/updatePwd.jsp=authc
                    /admin/*.jsp=roles[4]
                    /user/teacher.jsp=perms[2]
                    
                value>
            property>
        bean>
    
        
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    beans>
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    6、Myrealm

    package com.xnx.ssm.shiro;
    
    import com.xnx.ssm.biz.UserBiz;
    import com.xnx.ssm.model.User;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.util.ByteSource;
    
    import java.util.Set;
    
    /**
     * @author xnx
     * @create 2022-08-25 18:16
     */
    public class Myrealm extends AuthorizingRealm {
        private UserBiz userBiz;
    
        public UserBiz getUserBiz() {
            return userBiz;
        }
    
        public void setUserBiz(UserBiz userBiz) {
            this.userBiz = userBiz;
        }
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            System.out.println("用户授权...");
            String username = principals.getPrimaryPrincipal().toString();
            User user = userBiz.queryByName(username);
            Set<String> roles = userBiz.getRolesByUserId(user.getUsername());
            Set<String> pers = userBiz.getPersByUserId(user.getUsername());
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            info.setRoles(roles);
            info.setStringPermissions(pers);
            return info;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            System.out.println("身份验证...");
            String username = token.getPrincipal().toString();
            String password = token.getCredentials().toString();
            User user = userBiz.queryByName(username);
            AuthenticationInfo info=new SimpleAuthenticationInfo(
                    user.getUsername(),
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName()
            );
            return info;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    运行效果:
    在这里插入图片描述
    在这里插入图片描述

    二、Shiro的注解式开发

    1、springmvc-servlet.xml

    
    <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">
        
        
        <aop:aspectj-autoproxy/>
        <context:component-scan base-package="com.xnx.ssm"/>
    
        
        
        
        <mvc:annotation-driven>mvc:annotation-driven>
    
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            
            <property name="viewClass"
                      value="org.springframework.web.servlet.view.JstlView">property>
            <property name="prefix" value="/"/>
            <property name="suffix" value=".jsp"/>
        bean>
    
        
        
        
        
        <mvc:resources location="/static/" mapping="/js/**"/>
    
        
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            
            <property name="defaultEncoding" value="UTF-8">property>
            
            <property name="maxUploadSize" value="52428800">property>
            
            <property name="resolveLazily" value="true"/>
        bean>
    
        
        
        
       
    
        
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="mappingJackson2HttpMessageConverter"/>
                list>
            property>
        bean>
        <bean id="mappingJackson2HttpMessageConverter"
              class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
           
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8value>
                    <value>text/json;charset=UTF-8value>
                    <value>application/json;charset=UTF-8value>
                list>
            property>
        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>
    
    
    beans>
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118

    2、ShiroController

    package com.xnx.ssm.web;
    
    import org.apache.shiro.authz.annotation.Logical;
    import org.apache.shiro.authz.annotation.RequiresPermissions;
    import org.apache.shiro.authz.annotation.RequiresRoles;
    import org.apache.shiro.authz.annotation.RequiresUser;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * @author xnx
     * @create 2022-08-26 19:18
     */
    @RequestMapping("/shiro")
    @Controller
    public class ShiroController {
    
        @RequiresUser
        @RequestMapping("/passUser")
        public String passUser(HttpServletRequest request){
            System.out.println("身份认证通过..");
            return "admin/addUser";
        }
    
        @RequiresRoles(value = {"1","4"},logical = Logical.AND)
        @RequestMapping("/passRole")
        public String passRole(HttpServletRequest request){
            System.out.println("角色认证通过..");
            return "admin/addUser";
        }
    
        @RequiresPermissions(value = {"2"},logical = Logical.AND)
        @RequestMapping("/passPermission")
        public String permission(HttpServletRequest request){
            System.out.println("权限认证通过..");
            return "admin/addUser";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    运行效果:
    在这里插入图片描述
    未登录:
    在这里插入图片描述

  • 相关阅读:
    2023年Q4软件测试一般性趋势
    先聊聊「堆栈」,再聊聊「逃逸分析」。Let’s Go!
    【torch】torch.nn.functional 中的unfold和fold直观理解
    安卓APP(3)——安卓布局控件
    数学建模学习(83):模拟退火算法,最详细版本
    Java 基础-语法-运算符
    mysql数据类型的一些坑
    版本控制Git
    IOT跨平台组件设计方案
    JVM概念
  • 原文地址:https://blog.csdn.net/weixin_67677668/article/details/126549743