Use AOP+custom annotations to complete spring boot interface permission verification

created at 09-14-2021 views: 1

The record uses AOP+custom annotations to complete the permission verification of the interface, the code is as follows:

Add the required dependencies to the pom file:

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.9</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

First customize the annotation @MyAnnotation, the required parameters can be set in the annotation:

package com.itcq.aop;

import java.lang.annotation.*;

//Define the range of annotations that can be used
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {

    String name();
}

Define MyAnnotationService that parses annotations to complete the logic of interface permission verification. Here I am getting the user_name parameter in the header of the interface request to verify:

package com.itcq.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class MyAnnotationService {

    //The entry point expression determines whether to use the annotation method to cut or to cut all the classes and methods under a certain path. The method must return void type
    @Pointcut("@annotation(com.itcq.aop.MyAnnotation)")
    private void roleCheckCut() {};

    //Defines the processing logic of the aspect. That is, the @MyAnnotation annotation is added to the method, and permission verification will be performed
    @Around("roleCheckCut()")
    public Object operateAuth(ProceedingJoinPoint pjp) throws Throwable {

        //print log
        Signature signature = pjp.getSignature();
        String className = pjp.getTarget().getClass().getSimpleName();
        String methodName = signature.getName();
        log.info("className:{},methodName:{}", className, methodName);

        //Get the user_name parameter in the header of the interface request for verification
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userName = request.getHeader("user_name");
        //Here you can configure the roles that can be released by Apollo
        if (!"hwy".equals(userName)) {
            throw new Exception(userName+"Permission check failed");
        }
        return pjp.proceed();
    }
}

Finally, write a test method in the controller layer, and use postman to test the interface:

package com.itcq.controller;

import com.itcq.aop.MyAnnotation;
import com.itcq.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test")
    @MyAnnotation(name = "HWY")
    public String testMethod(@RequestHeader(name = "user_name") String userName,
                             @RequestParam(name = "user_age") Integer userAge) {

        return testService.testMethod(userName, userAge);
    }
}

The test results of the two different request parameters are as follows:

The return result when the parameters are correct:

eturn result

The return result when the parameter is incorrect, the interface reports an error, and the console output:

failed result

info

It can be found that the permission verification of the interface is completed in the form of AOP+custom annotations. Of course, this is only a relatively rudimentary application. AOP+custom annotations still have a lot of room for exploration.

Please log in to leave a comment.