• shiro授权


    目录

    1、shiro授权角色、权限

    1.1、UserMapper

    1.2、UserMapper

    1.3、UserBiz

    1.4、UserBizImpl

    1.5、applicationContext-shiro

    1.6、Myrealm

    2、shiro的注解式开发

    2.1、springmvc-servlet

    2.2、shiroController


    1、shiro授权角色、权限

    首先看一下数据库表

     

    1.1、UserMapper

    1. package com.ssr.ssm.mapper;
    2. import com.ssr.ssm.model.User;
    3. import org.springframework.stereotype.Repository;
    4. import java.util.Set;
    5. @Repository
    6. public interface UserMapper {
    7. int deleteByPrimaryKey(Integer userid);
    8. int insert(User record);
    9. int insertSelective(User record);
    10. User selectByPrimaryKey(Integer userid);
    11. User queryByName(String userName);
    12. int updateByPrimaryKeySelective(User record);
    13. int updateByPrimaryKey(User record);
    14. Set getRolesByUserId(String userName);
    15. Set getPersByUserId(String userName);
    16. }

    1.2、UserMapper

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

    1.3、UserBiz

    1. package com.ssr.ssm.biz;
    2. import com.ssr.ssm.model.User;
    3. import java.util.Set;
    4. /**
    5. * @author ssr
    6. * @create 2022-08-25 18:06
    7. */
    8. public interface UserBiz {
    9. int deleteByPrimaryKey(Integer userid);
    10. int insert(User record);
    11. int insertSelective(User record);
    12. User selectByPrimaryKey(Integer userid);
    13. User queryByName(String userName);
    14. int updateByPrimaryKeySelective(User record);
    15. int updateByPrimaryKey(User record);
    16. Set getRolesByUserId(String userName);
    17. Set getPersByUserId(String userName);
    18. }

    1.4、UserBizImpl

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

    1.5、applicationContext-shiro

    1. "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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="shiroRealm" class="com.ssr.ssm.shiro.Myrealm">
    6. <property name="userBiz" ref="UserService" />
    7. <property name="credentialsMatcher">
    8. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    9. <property name="hashAlgorithmName" value="md5"/>
    10. <property name="hashIterations" value="1024"/>
    11. <property name="storedCredentialsHexEncoded" value="true"/>
    12. bean>
    13. property>
    14. bean>
    15. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    16. <property name="realm" ref="shiroRealm" />
    17. bean>
    18. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    19. <property name="securityManager" ref="securityManager" />
    20. <property name="loginUrl" value="/login"/>
    21. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    22. <property name="filterChainDefinitions">
    23. <value>
    24. /user/login=anon
    25. /user/updatePwd.jsp=authc
    26. /admin/*.jsp=roles[4]
    27. /user/teacher.jsp=perms[2]
    28. value>
    29. property>
    30. bean>
    31. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    32. beans>

    1.6、Myrealm

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

     

    2、shiro的注解式开发

    2.1、springmvc-servlet

    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. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. 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">
    8. <!-- 通过context:component-scan元素扫描指定包下的控制器-->
    9. <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    10. <aop:aspectj-autoproxy/>
    11. <context:component-scan base-package="com.ssr.ssm"/>
    12. <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    13. <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
    14. <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
    15. <mvc:annotation-driven></mvc:annotation-driven>
    16. <!--3) ViewResolver -->
    17. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    18. <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
    19. <property name="viewClass"
    20. value="org.springframework.web.servlet.view.JstlView"></property>
    21. <property name="prefix" value="/"/>
    22. <property name="suffix" value=".jsp"/>
    23. </bean>
    24. <!--4) 单独处理图片、样式、js等资源 -->
    25. <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    26. <!--<mvc:resources location="/images/" mapping="/images/**"/>-->
    27. <!--<mvc:resources location="/js/" mapping="/js/**"/>-->
    28. <mvc:resources location="/static/" mapping="/js/**"/>
    29. <!--文件上传:多功能解析器-->
    30. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    31. <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
    32. <property name="defaultEncoding" value="UTF-8"></property>
    33. <!-- 文件最大大小(字节) 1024*1024*50=50M-->
    34. <property name="maxUploadSize" value="52428800"></property>
    35. <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
    36. <property name="resolveLazily" value="true"/>
    37. </bean>
    38. <!--配置拦截器-->
    39. <!--<mvc:interceptors>
    40. &lt;!&ndash;针对于所有的请求进行拦截&ndash;&gt;
    41. <bean class="com.ssr.ssm.intercept.OneHandlerInterceptor"></bean>
    42. </mvc:interceptors>-->
    43. <!--配置拦截器链-->
    44. <!-- <mvc:interceptors>
    45. <mvc:interceptor>
    46. <mvc:mapping path="/**"/>
    47. <bean class="com.ssr.ssm.intercept.OneHandlerInterceptor"></bean>
    48. </mvc:interceptor>
    49. <mvc:interceptor>
    50. <mvc:mapping path="/clz/**"/>
    51. <bean class="com.ssr.ssm.intercept.TwoHandlerInterceptor"></bean>
    52. </mvc:interceptor>
    53. </mvc:interceptors>-->
    54. <!--支持json数据返回的适配器-->
    55. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    56. <property name="messageConverters">
    57. <list>
    58. <ref bean="mappingJackson2HttpMessageConverter"/>
    59. </list>
    60. </property>
    61. </bean>
    62. <bean id="mappingJackson2HttpMessageConverter"
    63. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    64. <!-- 处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
    65. <property name="supportedMediaTypes">
    66. <list>
    67. <value>text/html;charset=UTF-8</value>
    68. <value>text/json;charset=UTF-8</value>
    69. <value>application/json;charset=UTF-8</value>
    70. </list>
    71. </property>
    72. </bean>
    73. <!--统一异常处理-->
    74. <!-- springmvc提供的简单异常处理器 -->
    75. <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    76. &lt;!&ndash; 定义默认的异常处理页面 &ndash;&gt;
    77. <property name="defaultErrorView" value="error"/>
    78. &lt;!&ndash; 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception &ndash;&gt;
    79. <property name="exceptionAttribute" value="ex"/>
    80. &lt;!&ndash; 定义需要特殊处理的异常,这是重要点 &ndash;&gt;
    81. <property name="exceptionMappings">
    82. <props>
    83. <prop key="java.lang.RuntimeException">error</prop>
    84. </props>
    85. &lt;!&ndash; 还可以定义其他的自定义异常 &ndash;&gt;
    86. </property>
    87. </bean>-->
    88. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    89. depends-on="lifecycleBeanPostProcessor">
    90. <property name="proxyTargetClass" value="true"></property>
    91. </bean>
    92. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    93. <property name="securityManager" ref="securityManager"/>
    94. </bean>
    95. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    96. <property name="exceptionMappings">
    97. <props>
    98. <prop key="org.apache.shiro.authz.UnauthorizedException">
    99. unauthorized
    100. </prop>
    101. </props>
    102. </property>
    103. <property name="defaultErrorView" value="unauthorized"/>
    104. </bean>
    105. </beans>

    2.2、shiroController

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

     

     

  • 相关阅读:
    Python实现酷炫的动态交互式数据可视化,附代码
    Reggie外卖项目 —— 分类管理模块之分类信息分页查询功能
    MySQL约束constraint
    DHT11数字温湿度传感器(三引脚)与cc2530芯片开发板
    MQ - 10 RocketMQ的架构设计与实现
    docker基础命令
    实战经验分享FastAPI 是什么
    基于单片机的贪吃蛇设计
    java-net-php-python-springboot区校企大型仪器智慧共享平台计算机毕业设计程序
    .NET周报【11月第1期 2022-11-07】
  • 原文地址:https://blog.csdn.net/m0_65774688/article/details/126577607