• Shiro授权--ssm


    目录

    一、Shiro授权

    步骤:

    1、Mapper层、service层

    2、shiro 的 授权方式

    3、测试

    二、shiro注解式开发

    1)将对应注解添加到指定需要权限控制的方法上

    身份认证:requireUser

    角色认证:requireRole

    权限认证: requirePermission

    (2)在SpringMVC.xml中添加拦截相关配置

    controller层

    Springmvc-servlet.xml:


    一、Shiro授权

    授角色:用户具备哪些角色

    1. SELECT roleid from t_shiro_user u,t_shiro_user_role ur
    2. where u.userid = ur.userid and u.username = 'zdm'


    授权限:用户具备哪些权限

    1. SELECT rp.perid from t_shiro_user u, t_shiro_user_role ur,t_shiro_role_permission rp
    2. where u.userid = ur.userid and ur.roleid= rp.roleid and u.username = 'ww

    步骤:

    1、Mapper层、service层

    UserMapper.xml:

    1. <select id="selectRoleIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
    2. SELECT roleid from t_shiro_user u,t_shiro_user_role ur
    3. where u.userid = ur.userid and u.username = #{userName}
    4. </select>
    5. <select id="selectPerIdsByUserName" resultType="java.lang.String" parameterType="java.lang.String" >
    6. SELECT rp.perid from t_shiro_user u, t_shiro_user_role ur,t_shiro_role_permission rp
    7. where u.userid = ur.userid and ur.roleid= rp.roleid and u.username = #{userName}
    8. </select>

     UserMapper :

    1. package com.ycx.mapper;
    2. import com.ycx.model.User;
    3. import org.apache.ibatis.annotations.Param;
    4. import org.springframework.stereotype.Repository;
    5. import java.util.Set;
    6. @Repository
    7. public interface UserMapper {
    8. int deleteByPrimaryKey(Integer userid);
    9. int insert(User record);
    10. int insertSelective(User record);
    11. User selectByPrimaryKey(Integer userid);
    12. //通过账户名查询账户信息
    13. User queryUserByUserName (@Param("userName") String userName);
    14. //通过账户名查询对应的角色
    15. Set selectRoleIdsByUserName (@Param("userName") String userName);
    16. //通过账户名查询对应的权限
    17. Set selectPerIdsByUserName (@Param("userName") String userName);
    18. int updateByPrimaryKeySelective(User record);
    19. int updateByPrimaryKey(User record);
    20. }

    UserBiz : 

    1. package com.ycx.ssm.biz;
    2. import com.ycx.model.User;
    3. import java.util.Set;
    4. public interface UserBiz {
    5. int deleteByPrimaryKey(Integer userid);
    6. int insert(User record);
    7. int insertSelective(User record);
    8. User selectByPrimaryKey(Integer userid);
    9. User queryUserByUserName(String userName);
    10. int updateByPrimaryKeySelective(User record);
    11. int updateByPrimaryKey(User record);
    12. //通过账户名查询对应的角色
    13. Set selectRoleIdsByUserName (String userName);
    14. //通过账户名查询对应的权限
    15. Set selectPerIdsByUserName (String userName);
    16. }

    UserBizImpl :

    1. package com.ycx.ssm.biz.impl;
    2. import com.ycx.mapper.UserMapper;
    3. import com.ycx.model.User;
    4. import com.ycx.ssm.biz.UserBiz;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.Set;
    8. /**
    9. * @author 杨总
    10. * @create 2022-08-25 19:17
    11. */
    12. @Service("userBiz")
    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 queryUserByUserName(String userName) {
    34. return userMapper.queryUserByUserName(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.updateByPrimaryKeySelective(record);
    43. }
    44. @Override
    45. public Set<String> selectRoleIdsByUserName(String userName) {
    46. return userMapper.selectRoleIdsByUserName(userName);
    47. }
    48. @Override
    49. public Set<String> selectPerIdsByUserName(String userName) {
    50. return userMapper.selectPerIdsByUserName(userName);
    51. }
    52. }

    MyRealm :

    1. package com.ycx.shiro;
    2. import com.ycx.model.User;
    3. import com.ycx.ssm.biz.UserBiz;
    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 杨总
    16. * @create 2022-08-25 19:38
    17. */
    18. public class MyRealm extends AuthorizingRealm {
    19. public UserBiz userBiz;
    20. public UserBiz getUserBiz() {
    21. return userBiz;
    22. }
    23. public void setUserBiz(UserBiz userBiz) {
    24. this.userBiz = userBiz;
    25. }
    26. /**
    27. * 授权
    28. * @param principals
    29. * @return
    30. * shiro-web.ini
    31. */
    32. @Override
    33. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    34. String userName = principals.getPrimaryPrincipal().toString();//获取账户名
    35. Set<String> roleIds = userBiz.selectRoleIdsByUserName(userName);
    36. Set<String> perIds = userBiz.selectPerIdsByUserName(userName);
    37. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    38. // 将当前登录的权限交给shiro的授权器
    39. info.setStringPermissions(perIds);
    40. // 将当前登录的角色交给shiro的授权器
    41. info.setRoles(roleIds);
    42. return info;
    43. }
    44. /**
    45. * 认证
    46. * @param token
    47. * @return
    48. * @throws AuthenticationException
    49. * shiro.ini
    50. */
    51. @Override
    52. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    53. String userName = token.getPrincipal().toString();
    54. User user = null;
    55. try {
    56. user = userBiz.queryUserByUserName(userName);
    57. }catch (Exception e){
    58. e.printStackTrace();
    59. }
    60. AuthenticationInfo info=new SimpleAuthenticationInfo(
    61. user.getUsername(),
    62. user.getPassword(),
    63. ByteSource.Util.bytes(user.getSalt()),
    64. this.getName()//realm的名字
    65. );
    66. return info;
    67. }
    68. }

    2、shiro 的 授权方式

            注意:角色与权限的结果要与spring-shiro.xml的配置保持一致

                    角色:1,4

                    权限:1,2

    3、测试

     

     

     

     

     

     

     

    二、shiro注解式开发

    常用注解介绍:


     @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
     

     

    1)将对应注解添加到指定需要权限控制的方法上

    身份认证:requireUser

    角色认证:requireRole

    权限认证: requirePermission

    (2)在SpringMVC.xml中添加拦截相关配置

    controller层

    ShiroController :

    1. package com.ycx.controller;
    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. /**
    9. * @author 杨总
    10. * @create 2022-08-26 20:22
    11. */
    12. @RequestMapping("/shiro")
    13. @Controller
    14. public class ShiroController {
    15. // RequiresUser代表 当前方法只有登录后才能够访问
    16. // RequiresUser等价于spring-shiro.xml中的/user/updatePwd.jsp=authc配置
    17. @RequiresUser
    18. @RequestMapping("/passUser")
    19. public String passUser(){
    20. System.out.println("身份认证通过!");
    21. return "admin/addUser";
    22. }
    23. //RequiresRoles 代表当前方法只有具备指定的角色才能访问
    24. // RequiresRoles等价于spring-shiro.xml中的/admin/*.jsp=roles[4]配置
    25. @RequiresRoles(value = {"1","4"},logical = Logical.AND)
    26. @RequestMapping("/passRole")
    27. public String passRole(){
    28. System.out.println("角色认证通过!");
    29. return "admin/addUser";
    30. }
    31. //RequiresRoles 代表当前方法只有具备指定的权限才能访问
    32. // RequiresRoles等价于spring-shiro.xml中的/user/teacher.jsp=perms[2]配置
    33. @RequiresPermissions(value = {"2"},logical = Logical.AND)
    34. @RequestMapping("/passPermission")
    35. public String passPermission(){
    36. System.out.println("权限认证通过!");
    37. return "admin/addUser";
    38. }
    39. }

    Springmvc-servlet.xml:

    1. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    2. depends-on="lifecycleBeanPostProcessor">
    3. <property name="proxyTargetClass" value="true"></property>
    4. </bean>
    5. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    6. <property name="securityManager" ref="securityManager"/>
    7. </bean>
    8. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    9. <property name="exceptionMappings">
    10. <props>
    11. <prop key="org.apache.shiro.authz.UnauthorizedException">
    12. unauthorized
    13. </prop>
    14. </props>
    15. </property>
    16. <property name="defaultErrorView" value="unauthorized"/>
    17. </bean>

     

    再输入地址栏 http://localhost:8080/shiro/passUser

    进入成功

    再输入地址栏 http://localhost:8080/shiro/passRole : 

     

    再切换ls登录:

     

     登录进去之后:

     

     

    再输入地址栏 http://localhost:8080/shiro/passRole :

     

     错误又不一样了.

    如果换zdm登录:

    进入之后再输入地址栏 http://localhost:8080/shiro/passRole :

     

     

    可进行访问。

    退出再次登录zs,然后地址栏输入http://localhost:8080/shiro/passPermission:

    显示没有权限2.

    而登录ls,再次输入:

     

     则有用户新增。

    如果把AND改为OR:

     再次登录zs时,/shiro/passRole

     

      之前是不可访问的,现在可访问了。

  • 相关阅读:
    每个后端都应该了解的OpenResty入门以及网关安全实战
    红细胞膜包裹仿生型六价铬还原去除剂/磁性纳米马达/PFC高负载的聚合物仿生纳米颗粒的研究
    推荐系统(LLM去偏?) | (WSDM24)预训练推荐系统:因果去偏视角
    应对出海安全合规挑战,兆珑科技为什么选择了亚马逊云科技?
    Python GDAL读取栅格数据并基于质量评估波段QA对指定数据加以筛选掩膜
    java金融业撮合交易系统计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
    《机器学习》阅读笔记系列一
    Java高级面试问题
    2 万字 + 30 张图 | 细聊 MySQL undo log、redo log、binlog 有什么用?
    “交叉轮”轮融资后,哪吒汽车能否脚踏“风火轮”续写逆袭故事?
  • 原文地址:https://blog.csdn.net/m0_67477525/article/details/126555738