Shiro之@RequiresPermissions注解原理详解

2023-11-08

前言

shiro为我们提供了几个权限注解,如下图:
在这里插入图片描述
这几个注解原理都类似,这里我们讲解@RequiresPermissions的原理。

铺垫

第一
首先要清楚@RequiresPermissions的基本用法。就是在Controller的方法里,加上@RequiresPermissions注解,并写上权限标识。那么,有该权限标识的用户,才能访问到请求。如下图:
在这里插入图片描述
第二
先剧透一下,@RequiresPermissions注解的原理是使用了Spring的AOP进行了增强。来判断当前用户是否有该权限标识。我们复习一下Spring的AOP原理。AOP的核心流程是ReflectiveMethodInvocation类中的proceed方法。该方法会遍历加强集合,执行每一个加强的方法。不熟悉的可以查看这篇博客:《Spring之Joinpoint类详解》

执行流程分析

有了上面的铺垫,我们开始从源码分析其执行流程。
首先,断点打到ReflectiveMethodInvocation类的proceed方法这里,因为要对代理对象进行增强,必定要走这里。然后发送请求,进入断点,我们先看加强链上有哪些元素:
在这里插入图片描述
第一个Expose开头的对象,是Spring自己生成的元素,我们无需关注。第二个元素,就是加强@RequiresPermissions而生成的元素。看该类的源码:

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.shiro.spring.security.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.aop.AnnotationResolver;
import org.apache.shiro.authz.aop.*;
import org.apache.shiro.spring.aop.SpringAnnotationResolver;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Allows Shiro Annotations to work in any <a href="http://aopalliance.sourceforge.net/">AOP Alliance</a>
 * specific implementation environment (for example, Spring).
 *
 * @since 0.2
 */
public class AopAllianceAnnotationsAuthorizingMethodInterceptor
        extends AnnotationsAuthorizingMethodInterceptor implements MethodInterceptor {

    public AopAllianceAnnotationsAuthorizingMethodInterceptor() {
        List<AuthorizingAnnotationMethodInterceptor> interceptors =
                new ArrayList<AuthorizingAnnotationMethodInterceptor>(5);

        //use a Spring-specific Annotation resolver - Spring's AnnotationUtils is nicer than the
        //raw JDK resolution process.
        AnnotationResolver resolver = new SpringAnnotationResolver();
        //we can re-use the same resolver instance - it does not retain state:
        interceptors.add(new RoleAnnotationMethodInterceptor(resolver));
        interceptors.add(new PermissionAnnotationMethodInterceptor(resolver));
        interceptors.add(new AuthenticatedAnnotationMethodInterceptor(resolver));
        interceptors.add(new UserAnnotationMethodInterceptor(resolver));
        interceptors.add(new GuestAnnotationMethodInterceptor(resolver));

        setMethodInterceptors(interceptors);
    }
    /**
     * Creates a {@link MethodInvocation MethodInvocation} that wraps an
     * {@link org.aopalliance.intercept.MethodInvocation org.aopalliance.intercept.MethodInvocation} instance,
     * enabling Shiro Annotations in <a href="http://aopalliance.sourceforge.net/">AOP Alliance</a> environments
     * (Spring, etc).
     *
     * @param implSpecificMethodInvocation AOP Alliance {@link org.aopalliance.intercept.MethodInvocation MethodInvocation}
     * @return a Shiro {@link MethodInvocation MethodInvocation} instance that wraps the AOP Alliance instance.
     */
    protected org.apache.shiro.aop.MethodInvocation createMethodInvocation(Object implSpecificMethodInvocation) {
        final MethodInvocation mi = (MethodInvocation) implSpecificMethodInvocation;

        return new org.apache.shiro.aop.MethodInvocation() {
            public Method getMethod() {
                return mi.getMethod();
            }

            public Object[] getArguments() {
                return mi.getArguments();
            }

            public String toString() {
                return "Method invocation [" + mi.getMethod() + "]";
            }

            public Object proceed() throws Throwable {
                return mi.proceed();
            }

            public Object getThis() {
                return mi.getThis();
            }
        };
    }

    /**
     * Simply casts the method argument to an
     * {@link org.aopalliance.intercept.MethodInvocation org.aopalliance.intercept.MethodInvocation} and then
     * calls <code>methodInvocation.{@link org.aopalliance.intercept.MethodInvocation#proceed proceed}()</code>
     *
     * @param aopAllianceMethodInvocation the {@link org.aopalliance.intercept.MethodInvocation org.aopalliance.intercept.MethodInvocation}
     * @return the {@link org.aopalliance.intercept.MethodInvocation#proceed() org.aopalliance.intercept.MethodInvocation.proceed()} method call result.
     * @throws Throwable if the underlying AOP Alliance <code>proceed()</code> call throws a <code>Throwable</code>.
     */
    protected Object continueInvocation(Object aopAllianceMethodInvocation) throws Throwable {
        MethodInvocation mi = (MethodInvocation) aopAllianceMethodInvocation;
        return mi.proceed();
    }

    /**
     * Creates a Shiro {@link MethodInvocation MethodInvocation} instance and then immediately calls
     * {@link org.apache.shiro.authz.aop.AuthorizingMethodInterceptor#invoke super.invoke}.
     *
     * @param methodInvocation the AOP Alliance-specific <code>methodInvocation</code> instance.
     * @return the return value from invoking the method invocation.
     * @throws Throwable if the underlying AOP Alliance method invocation throws a <code>Throwable</code>.
     */
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        org.apache.shiro.aop.MethodInvocation mi = createMethodInvocation(methodInvocation);
        return super.invoke(mi);
    }
}

可以看出,这个类实现了MethodInterceptor接口。那么,其invoke方法,就是对原对象方法的增强。点进invoke方法,最后调到了AnnotationsAuthorizingMethodInterceptor类的assertAuthorized方法,如下:

protected void assertAuthorized(MethodInvocation methodInvocation) throws AuthorizationException {
        //default implementation just ensures no deny votes are cast:
        Collection<AuthorizingAnnotationMethodInterceptor> aamis = getMethodInterceptors();
        if (aamis != null && !aamis.isEmpty()) {
            for (AuthorizingAnnotationMethodInterceptor aami : aamis) {
                if (aami.supports(methodInvocation)) {
                    aami.assertAuthorized(methodInvocation);
                }
            }
        }
    }

在这里,会遍历是否有前言中截图的那几个注解,如果有的话,则调用相应的注解Handler去处理相应的逻辑。@RequiresPermissions的Handler的处理逻辑就是调用Realm中定义的权限获取方法,判断是否有注解中的标识,具体的调用Realm流程不再解析,前面博客已经解析过。
这样,就对@RequiresPermissions注解的方法进行了增强。

@RequiresPermissions切面

使用AOP,一定要有切面,这样Spring在实例化bean过程中,才会生成代理对象和加强链。Shiro的切面是AuthorizationAttributeSourceAdvisor类,需要加入Spring容器中管理,配置如下:

 /**
     * 开启Shiro注解通知器
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            @Qualifier("securityManager") SecurityManager securityManager)
    {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

下面分析这个类源码。前面博客说过,Advisor切面的两大核心就是切点pointcut和增强advice。我们看AuthorizationAttributeSourceAdvisor 的这两个核心在哪儿:

 /**
     * Create a new AuthorizationAttributeSourceAdvisor.
     */
    public AuthorizationAttributeSourceAdvisor() {
        setAdvice(new AopAllianceAnnotationsAuthorizingMethodInterceptor());
    }

这里设置了增强advice。正是我们上面分析的AopAllianceAnnotationsAuthorizingMethodInterceptor类。

public boolean matches(Method method, Class targetClass) {
        Method m = method;

        if ( isAuthzAnnotationPresent(m) ) {
            return true;
        }

        //The 'method' parameter could be from an interface that doesn't have the annotation.
        //Check to see if the implementation has it.
        if ( targetClass != null) {
            try {
                m = targetClass.getMethod(m.getName(), m.getParameterTypes());
                return isAuthzAnnotationPresent(m) || isAuthzAnnotationPresent(targetClass);
            } catch (NoSuchMethodException ignored) {
                //default return value is false.  If we can't find the method, then obviously
                //there is no annotation, so just use the default return value.
            }
        }

        return false;
    }

matches方法定义了切点。就是在对@RequiresPermissions等注解收集,然后判断是不是切点。这样,切面就分析完了。

总结

shiro定义了AuthorizationAttributeSourceAdvisor 切面,在切面里,定义了AopAllianceAnnotationsAuthorizingMethodInterceptor增强,来查询Realm中用户的权限等信息,判断是否和参数中的数据匹配。定义了matches方法,来收集@RequiresPermissions等注解。
在Spring实例化Bean时,执行BeanPostProcessor的postProcessAfterInitialization方法生成代理对象时(循环依赖的情况除外),就会找到shiro定义的切面,生成相应的代理对象,当执行方法时,就会走增强的方法,进行方法增强。
所以对于shiro框架的使用者而言,只需将AuthorizationAttributeSourceAdvisor 切面加入到Spring容器,然后在Realm中定义用户的权限查询方法。然后在需要的方法上加@RequiresPermissions注解,就可以进行权限的控制了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Shiro之@RequiresPermissions注解原理详解 的相关文章

  • Shiro实战学习笔记(4)- 整合springboot(1)

    1 shiro整合spring boot gt
  • SpringMVC+Apache Shiro+JPA(hibernate)案例教学(一)整合配置

    序 关于标题 说是教学 实在愧不敢当 但苦与本人文笔有限 实在找不到更合理 谦逊的词语表达 只能先这样定义了 其实最真实的想法 只是希望这个关键词能让更多的人浏览到这篇文章 也算是对于自己写文章的一个肯定吧 关于内容 再写这系列文章之前 本
  • shiro标签页点击报错: No SecurityManager accessible to the calling code...

    shiro按钮配置标签报错问题 问题 最近的项目需要将按钮也动态配置进去 我按照网上的步骤加上shiro的taglib标签 然后在该页面的某个按钮上加上
  • shiro和thymealeaf整合

    shiro和thymealeaf整合 一 加入依赖
  • SpringBoot整合shiro-spring-boot-web-starter启动报错

    最近在做一个SpringBoot整合常用框架的系统 在整合Shiro时启动就报错 现将解决办法总结如下 SpringBoot使用的是最新的2 3 4版本 Shiro使用的是shiro spring boot web starter1 6 0
  • shiro配置文件shiro.ini简介说明

    转自 shiro配置文件shiro ini简介说明 下文笔者讲述shiro配置文件shiro ini的简介说明 如下所示 shiro ini 是一个shiro的配置文件 它通常放在classpath路径下 shiro ini配置文件包含以下
  • Apache Shiro(三)——Spring Boot 与 Shiro的 整合

    在了解了Apache Shiro的架构 认证 授权之后 我们来看一下Shiro与Web的整合 下面以Spring Boot为例 介绍一下Spring Boot 与 Shiro的 整合 一 创建一个Spring Boot项目 可以使用IDEA
  • Shiro权限框架-Springboot集成Shiro(5)

    1 技术栈 主框架 springboot 响应层 springMVC 持久层 mybatis 事务控制 jta 前端技术 easyui 2 数据库设计 1 数据库图解 sh user 用户表 一个用户可以有多个角色 sh role 角色表
  • 权限系统与RBAC模型概述[绝对经典]

    0 前言 一年前 我负责的一个项目中需要权限管理 当时凭着自己的逻辑设计出了一套权限管理模型 基本原理与RBAC非常相似 只是过于简陋 当时google了一些权限管理的资料 从中了解到早就有了RBAC这个东西 可惜一直没狠下心来学习 更详细
  • shiro SecurityManager简介说明

    转自 shiro SecurityManager简介说明 下文笔者讲述Shiro SecurityManager的相关简介说明 如下所示 SecurityManager是Shiro框架的核心 典型的Facade模式 Shiro通过Secur
  • Java面试题--shiro

    Shiro可以做哪些工作 Shiro可以帮助我们完成 认证 授权 加密 会话管理 与Web集成 缓存等 shiro有哪些组件 Authentication 身份认证 登录 验证用户是不是拥有相应的身份 Authorization 授权 即权
  • Shiro中Session和Cache

    Session是一种状态保持机制 参考文章Session是什么可知Session和Web服务也没有必然关系 Shiro本身的Security Manager也可以脱离Servlet自己管理Session 根据Security Manager
  • shiro使用自定义realm实现数据认证

    自定义realm实现数据认证 在开发中 有时会与一些nosql或者其他地方保存的数据进行认证 这时候 shiro定义的那些realm类可能不能满足实际的功能需求 这时候我们可以通过自定义一个realm来沟通这些数据 实现认证和权限控制 首先
  • Shiro 如何对Jsp页面标签授权呢?

    转自 Shiro 如何对Jsp页面标签授权呢 下文笔者讲述jsp页面标签授权的方法分享 如下所示 shiro中使用Jsp页面标签授权首先需要导入标签库 常见的Shiro标签
  • 关于shiro doGetAuthorizationInfo授权方法和doGetAuthenticationInfo登陆认证方法的执行时机

    1 默认情况下不关闭shiro session 登陆时生成JESSIONID 执行doGetAuthorizationInfo的时机 1 subject hasRole admin 或 subject isPermitted admin 自
  • Apache Shiro 和 SSO

    Apache Shiro 是一个 Java 安全框架 支持 SSO 我有多个子域 每个子域都有单独的应用程序运行 我如何使用 Apache Shiro Web 过滤器 或任何其他过滤器 来提供单点登录 在使用 Apache Shiro 之前
  • Shiro JndiLdapRealm 针对 LDAP 的授权

    The Shiro 类 JndiLdapRealm 的 JavaDoc明确表示默认情况下禁用授权 并且用户应通过子类化和覆盖 LDAP 服务器来实现授权JndiLdapRealm doGetAuthorizationInfo方法 是否有示例
  • 将 Shiro 的 PasswordMatcher 与自定义领域结合使用

    我使用 Apache Shiro 和自定义 JDBC 领域来从数据库中检索用户的盐 密码 哈希算法名称和哈希迭代次数 这些数据都存储为单独的列 问题是我不确定在使用 PasswordMatcher 验证用户密码与数据库中存储的密码是否匹配时
  • 使用 Shiro 登录后重定向到最后访问的页面

    使用 apache shiro 登录并重定向到最后访问的页面的更好方法是什么 我只有这个 SecurityUtils getSubject login new UsernamePasswordToken username password
  • 定制/扩展Spring对shiro的@Async支持

    我正在使用Spring的 EnableAsync异步执行方法的功能 为了安全起见 我使用 Apache Shiro 在异步执行的代码中 我需要访问附加到触发异步调用的线程的 Shiro 主题 Shiro 支持通过将主题与主题相关联来在不同线

随机推荐

  • Linux性能检测常用的10个基本命令

    1 uptime 该命令可以大致的看出计算机的整体负载情况 load average后的数字分别表示计算机在1min 5min 15min内的平均负载 2 dmesg tail 打印内核环形缓存区中的内容 可以用来查看一些错误 上面的例子中
  • vue3组件库搭建并且发布到npm保姆教程连载一

    前言 小时候的梦想是拥有一个自己的组件库 开玩笑哈 接触前端后 很多时候在npm install的时候 我在想我们安装的这些依赖发布者是如何将依赖发布到npm 并且可以让别人使用的 未知是让人害怕的 经过一系列学习和探索后 我也拥有了自己的
  • 【python数据挖掘课程】二十六.基于SnowNLP的豆瓣评论情感分析

    这是 Python数据挖掘课程 系列文章 前面很多文章都讲解了分类 聚类算法 而这篇文章主要讲解如何调用SnowNLP库实现情感分析 处理的对象是豆瓣 肖申克救赎 的评论文本 文章比较基础 希望对你有所帮助 提供些思路 也是自己教学的内容
  • 全国青少年电子信息智能创新大赛(决赛)python·模拟三卷,含答案解析

    全国青少年电子信息智能创新大赛 决赛 python 模拟三卷 一 程序题 第一题 描述 现有 n 个人依次围成一圈玩游戏 从第 1 个人开始报数 数到第 m 个人出局 然 后从出局的下一个人开始报数 数到第 m 个人又出局 如此反复到只剩下
  • Google分布式三篇论文---BigTable

    Google s BigTable 原理 翻译 题记 google 的成功除了一个个出色的创意外 还因为有 Jeff Dean 这样的软件架构天才 官方的 Google Reader blog 中有对BigTable 的解释 这是Googl
  • TensorRT(2):TensorRT的使用流程

    TensorRT系列传送门 不定期更新 深度框架 TensorRT 文章目录 一 在线加载caffe模型 序列化保存到本地 二 反序列化直接加载保存后的trt模型 以caffe分类模型为例 简单介绍TRT的使用流程 这里不涉及量化 就以fp
  • 测试的艺术:代码检查、走查与评审

    软件开发人员通常不会考虑的一种测试形式 人工测试 大多数人都以为 因为程序是为了供机器执行而编写的 那么也该由机器来对程序进行测试 这种想法是有问题的 人工测试方法在暴露错误方面是很有成效的 实际上 大多数的软件项目都应使用到一下的人工测试
  • 详解Shell 脚本中 “$” 符号的多种用法

    通常情况下 在工作中用的最多的有如下几项 1 表示执行脚本传入参数的个数 2 表示执行脚本传入参数的列表 不包括 0 3 表示进程的id Shell本身的PID ProcessID 即脚本运行的当前 进程ID号 4 Shell最后运行的后台
  • 解决uni-toast被弹窗组件遮挡

    在App vue uni toast设置层级比popup高就行 uni toast z index 999999
  • 输入文本就可建模渲染了?!OpenAI祭出120亿参数魔法模型!

    转自 https new qq com omn 20210111 20210111A0CBRD00 html 2021刚刚开启 OpenAI又来放大招了 能写小说 哲学语录的GPT 3已经不足为奇 那就来一个多模态 图像版GPT 3 今天
  • 微信小程序事件和页面跳转

    一 页面跳转 1 非TabBar页面 一个小程序拥有多个页面 我们通过wx navigateTo进入一个新的页面 我们通过下边点击事件实现页面跳转进行代码实现及参考 wx navigateBack 回退到上一个页面 wx redirectT
  • 【单片机毕业设计】【mcuclub-310】红外遥控器

    设计简介 项目名 基于单片机的红外遥控器的设计 标准版 单片机 STC89C52 功能简介 1 利用红外发射电路 通过按不同的按键发送不同的数据值 2 利用红外接收电路 接收发送端发送的数据 3 通过数码管显示数据 资料预览 效果图 发送端
  • MiniGPT-4本地部署的实战方案

    大家好 我是herosunly 985院校硕士毕业 现担任算法研究员一职 热衷于机器学习算法研究与应用 曾获得阿里云天池比赛第一名 CCF比赛第二名 科大讯飞比赛第三名 拥有多项发明专利 对机器学习和深度学习拥有自己独到的见解 曾经辅导过若
  • Ubuntu22下OpenCV4.6.0+contrib模块编译安装

    目录 第一章 Ubuntu22下OpenCV4 6 0 contrib模块编译安装 第二章 ubuntu22下C kdevelop环境搭建 OpenCV示例 第三章 C 下OPENCV驱动调用海康GigE工业相机 文章目录 目录 Ubunt
  • K8S常用资源认识

    文章目录 一 Namespace 二 Pod 三 Label 四 Deployment 五 Service 一 Namespace namespace是kubernetes系统中的一种非常重要的资源 它的主要作用是用来实现多套环境的资源隔离
  • 基于栈与基于寄存器的指令集架构

    用C的语法来写这么一个语句 C代码 a b c 如果把它变成这种形式 add a b c 那看起来就更像机器指令了 对吧 这种就是所谓 三地址指令 3 address instruction 一般形式为 op dest src1 src2
  • python 模块和包

    文章目录 前言 模块 什么是模块 导入模块 import 导入模块 from 模块名 import 功能 from 模块名 import as定义别名 制作模块 模块的定位顺序 all 包 导入包 import 包名 模块 导入包 from
  • 打开Ubuntu18.04出现启动紫屏卡死不弹登录框问题

    1 进入grub高级模式 重启虚拟机 按esc进入 按 进入Ubuntu高级选项 2 选择recovery mode 3 选择root shell会话 输入root密码 4 编辑 etc gdm3 custom conf文件 将 Wayla
  • 5-快速排序

    假设有下面这样一排数据需要排序 3 7 6 1 2 9 1 2 6 排开常用的冒泡和选择排序 今天我们来试一下一种新的方法 快速排序 快速排序的思路如下 首先我们要先从这组数据中选出一个任意值X 然后以X为分界 比X小的数据排到X的左半边
  • Shiro之@RequiresPermissions注解原理详解

    前言 shiro为我们提供了几个权限注解 如下图 这几个注解原理都类似 这里我们讲解 RequiresPermissions的原理 铺垫 第一 首先要清楚 RequiresPermissions的基本用法 就是在Controller的方法里