search
HomeJavajavaTutorialExtension of custom annotations based on shiro - detailed explanation with pictures and text

Extension based on shiro's custom annotations

Here we mainly adopt shiro's custom annotation solution. This article mainly solves the following problems.

  1. How to associate the page with the api interface through logic.

  2. Usage of shiro’s own annotations.

  3. How to write custom annotations.

How to associate pages with api interfaces through logic

In the structural relationship between tables, the page and interface tables are ultimately associated with the permissions table (For details, please see my previous article "Miscellaneous Talk about Permission Design").
Extension of custom annotations based on shiro - detailed explanation with pictures and textWe now hope to replace it with another solution to achieve a low cost while taking into account a certain degree of permission control. Here we introduce two concepts. Business module, Operation type.

  • Business module

    • Concept: Abstracting the business module in the system into a kind of data, we can Express it in the form of a string, for example: role management corresponds to role-manage, user management corresponds to user-manage, etc. We divide the business modules existing in the system through the "principle of least privilege" and finally form a batch of distributable data.

    • Principles of use: The api interface, page and function are essentially logically related to the business module. Therefore, we can use the api interface and page ( and function points) to perform logical matching to determine the relationship between the page and the interface.

  • Operation type

    • Concept: Abstract all operation types in the system into one We can also express this kind of data in the form of strings, for example: add corresponds to new addition, allot corresponds to allocation, etc. We divide all operation types in the system through "data licenses" according to business modules, and finally form a batch of distributable data.

    • Usage Principle: The page is the display, the function point is the action, and the interface is the resource provision for the final action. The resources to be called are determined through the "business module" , the "operation type" determines how the resource is used. Through the two, you can roughly and accurately determine whether the interface triggered by the function point of the page is within the authentication.

Now that these two concepts are proposed, what is their final actual use? Let us first think about it from the following perspectives.

  1. Is the data in the page table in the database or the api interface table true and valid?

  2. The actual use of the page or interface is based on the existence of functions or the existence of data in the database table.

  3. In the permission structure, is the only way to store "control objects" is the database?

Let's look at these issues from the conclusion. First of all, the "control object" can be stored not only in the database but also in the code or in the configuration file. It does not necessarily have to be In the database; then to answer the second question, when the interface information exists in the database but the server has not developed this interface, there is a problem with the database information itself, or the new interface in the database must be the server side The interface that has been deployed can take effect; then there is the first question, then the data in the "control object" table in the database is not necessarily true and valid. So we can come up with the following solution

  1. We can use the annotation form to supplement the data information of "Business Module" and "Operation Type" on the interface, Both types of information can be stored in constant classes.

  2. When adding and creating the page table structure and page function table structure in the database, add the "Business Module" and "Operation Type" fields .

  3. You can store the "business module" and "operation type" information in the dictionary table of the database.

  4. The addition of modules or operations will inevitably bring about the addition of interfaces, which will lead to a system deployment activity. This operation and maintenance cost cannot be reduced. It cannot be reduced by table structure.

Extension of custom annotations based on shiro - detailed explanation with pictures and text

However, this solution is only suitable for non-strong control interface projects. In strong control interface projects, the page and the interface must still be bound, although this will bring huge operation and maintenance costs. In addition, it can also be divided by interface routing rules, for example: /api/page/xxxx/ (only used for pages), /api/mobile/xxxxx (only used for mobile terminals) will classify interfaces that are only used by pages. This The class interface only performs authentication but not authorization, which can also achieve the purpose.

Usage of Shiro’s own annotations

After a theoretical idea is approved, the rest is put into technical practice. We use the security framework of Apache Shiro here. , applied in Spring Boot environment. Briefly explain the following annotations of Shiro.

##@RequiresAuthentication Acts on classes, methods, and instances. When called, the current subject must be authenticated. @RequiresGuest acts on classes, methods, and instances. When called, the subject can be in the guest state. @RequiresPermissions Acts on classes, methods, and instances. When calling, you need to determine whether the project contains the Permission (permission information) in the current interface. @RequiresRoles acts on classes, methods, and instances. When calling, you need to determine whether the subject contains the Role (role information) in the current interface. @RequiresUser acts on classes, methods, and instances. When calling, it is necessary to determine whether the subject is a user currently in the application.
    /**
     * 1.当前接口需要经过"认证"过程
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @RequiresAuthentication
    public String test(){
        return "恭喜你,拿到了参数信息";
    }
    
    /**
     * 2.1.当前接口需要经过权限校验(需包含 角色的查询 或 菜单的查询)
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @RequiresPermissions(value={"role:search","menu":"search"},logical=Logical.OR)
    public String test(){
        return "恭喜你,拿到了参数信息";
    }
    
    /**
     * 2.2.当前接口需要经过权限校验(需包含 角色的查询 与 菜单的查询)
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @RequiresPermissions(value={"role:search","menu":"search"},logical=Logical.OR)
    public String test(){
        return "恭喜你,拿到了参数信息";
    }
    
    /**
     * 3.1.当前接口需要经过角色校验(需包含admin的角色)
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @RequiresRoles(value={"admin"})
    public String test(){
        return "恭喜你,拿到了参数信息";
    }
    
    /**
     * 3.2.当前接口需要经过角色与权限的校验(需包含admin的角色,以及角色的查询 或 菜单的查询)
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @RequiresRoles(value={"admin"})
    @RequiresPermissions(value={"role:search","menu":"search"},logical=Logical.OR)
    public String test(){
        return "恭喜你,拿到了参数信息";
    }
Annotation name Function
In our actual use process, we actually only need to use @RequiresPermissions and @RequiresAuthentication. This annotation is enough, at the end of the previous section , we adopted a combination of business modules and operations to decouple the relationship between the page and the api interface, which is exactly the same as apache Shiro's approach. But we try not to use @RequiresRoles as much as possible, because there are too many combinations of roles, and the role name cannot be uniquely represented in the interface (it is difficult to specify that the interface belongs to a certain role, but you can definitely know that the interface belongs to certain business modules) Some operations.)

Now let’s review the entire operation process.

Extension of custom annotations based on shiro - detailed explanation with pictures and text

How to write custom annotations

But just having these 5 annotations in shiro is definitely not enough. In the actual use process, according to the needs, we will add our own unique business logic to the permission authentication. For convenience, we can use it in the form of custom annotations. This method is not only applicable to Apache Shiro, but also to many other frameworks such as Hibernate Validator, SpringMVC, and even we can write a verification system to verify permissions in aop. This is no problem. Therefore, custom annotations have a wide range of uses. But here, I only implement custom annotations suitable for it based on shiro.

  • Define annotation class

  • /**
     * 用于认证的接口的注解,组合形式默认是“或”的关系
     */
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Auth {
        /**
         * 业务模块
         * @return
         */
        String[] module();
        /**
         * 操作类型
         */
        String[] action();
    
    }
  • Define annotation processing class

  • /**
     * Auth注解的操作类
     */
    public class AuthHandler extends AuthorizingAnnotationHandler {
    
    
        public AuthHandler() {
            //写入注解
            super(Auth.class);
        }
    
        @Override
        public void assertAuthorized(Annotation a) throws AuthorizationException {
            if (a instanceof Auth) {
                Auth annotation = (Auth) a;
                String[] module = annotation.module();
                String[] action = annotation.action();
                //1.获取当前主题
                Subject subject = this.getSubject();
                //2.验证是否包含当前接口的权限有一个通过则通过
                boolean hasAtLeastOnePermission = false;
                for(String m:module){
                    for(String ac:action){
                        //使用hutool的字符串工具类
                        String permission = StrFormatter.format("{}:{}",m,ac);
                        if(subject.isPermitted(permission)){
                            hasAtLeastOnePermission=true;
                            break;
                        }
                    }
                }
                if(!hasAtLeastOnePermission){
                    throw new AuthorizationException("没有访问此接口的权限");
                }
    
            }
        }
    }
  • Define shiro interception processing class

  • /**
     * 拦截器
     */
    public class AuthMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
    
    
        public AuthMethodInterceptor() {
            super(new AuthHandler());
        }
    
        public AuthMethodInterceptor(AnnotationResolver resolver) {
            super(new AuthHandler(), resolver);
        }
    
        @Override
        public void assertAuthorized(MethodInvocation mi) throws AuthorizationException {
            // 验证权限
            try {
                ((AuthHandler) this.getHandler()).assertAuthorized(getAnnotation(mi));
            } catch (AuthorizationException ae) {
                if (ae.getCause() == null) {
                    ae.initCause(new AuthorizationException("当前的方法没有通过鉴权: " + mi.getMethod()));
                }
                throw ae;
            }
        }
    }
  • Define shiro’s aop aspect class

  • /**
     * shiro的aop切面
     */
    public class AuthAopInterceptor extends AopAllianceAnnotationsAuthorizingMethodInterceptor {
        public AuthAopInterceptor() {
            super();
            // 添加自定义的注解拦截器
            this.methodInterceptors.add(new AuthMethodInterceptor(new SpringAnnotationResolver()));
        }
    }
  • Define shiro's custom annotation startup class

  • /**
     * 启动自定义注解
     */
    public class ShiroAdvisor extends AuthorizationAttributeSourceAdvisor {
    
        public ShiroAdvisor() {
            // 这里可以添加多个
            setAdvice(new AuthAopInterceptor());
        }
    
        @SuppressWarnings({"unchecked"})
        @Override
        public boolean matches(Method method, Class targetClass) {
            Method m = method;
            if (targetClass != null) {
                try {
                    m = targetClass.getMethod(m.getName(), m.getParameterTypes());
                    return this.isFrameAnnotation(m);
                } catch (NoSuchMethodException ignored) {
    
                }
            }
            return super.matches(method, targetClass);
        }
    
        private boolean isFrameAnnotation(Method method) {
            return null != AnnotationUtils.findAnnotation(method, Auth.class);
        }
    }
The overall sequence of ideas: define
annotation class (define variables that can be used by the business) ->Defineannotation processing class(do business logic processing through variables in the annotation)->Defineannotation interceptor->defineaop aspect class->Finally define Shiro’s custom annotation enablement class. The writing ideas for other custom annotations are similar to this one.
Related recommendations:

Custom annotation mapping thinkPHP21 custom tag library import method detailed explanation

About custom annotations in Java Detailed introduction

Detailed explanation of shiro authorization implementation

The above is the detailed content of Extension of custom annotations based on shiro - detailed explanation with pictures and text. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Spring怎么实现定时任务Java Spring怎么实现定时任务May 24, 2023 pm 01:28 PM

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

Java axios与spring前后端分离传参规范是什么Java axios与spring前后端分离传参规范是什么May 03, 2023 pm 09:55 PM

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

Spring Boot与Spring Cloud的区别与联系Spring Boot与Spring Cloud的区别与联系Jun 22, 2023 pm 06:25 PM

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

Spring 最常用的 7 大类注解,史上最强整理!Spring 最常用的 7 大类注解,史上最强整理!Jul 26, 2023 pm 04:38 PM

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

Java Spring框架创建项目与Bean的存储与读取实例分析Java Spring框架创建项目与Bean的存储与读取实例分析May 12, 2023 am 08:40 AM

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

从零开始学Spring Cloud从零开始学Spring CloudJun 22, 2023 am 08:11 AM

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

Java Spring Bean生命周期管理的示例分析Java Spring Bean生命周期管理的示例分析Apr 18, 2023 am 09:13 AM

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有哪些spring设计模式有哪些Dec 29, 2023 pm 03:42 PM

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.