Abstract

  • Implement simple permission control
  • Implement simple logging

Access control

pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code

annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PermissionAnnotation{}
Copy the code

aspect

@Aspect
@Component
@Order(1)
public class PermissionFirstAdvice {

    @Pointcut("@annotation(xx.xx.xx.PermissionAnnotation)")
    private void permissionCheck(a) {}@Around("permissionCheck()")
    public Object permissionCheckFirst(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println(System.currentTimeMillis());

        // Get the request parameters
        Object[] objects = joinPoint.getArgs();
        String userName = (String) objects[0];

        if(! userName.equals("admin")) {
            return "Failure";
        }
        returnjoinPoint.proceed(); }}Copy the code

controller

@RestController
@RequestMapping(value = "/permission")
public class TestController {
    
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @PermissionsAnnotation()
    public String getGroupList(@RequestParam String userName) {
        return "Hello "+userName; }}Copy the code

The log

pom

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5. RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
    </dependencies>
Copy the code

aspect

@Aspect
@Component
public class OperLogAspect {

    // Operate pointcuts
    @Pointcut("@annotation(com.bothsavage.annotation.OperLog)")
    public void operLogPoinCut(a) {}


    // Return the notification normally
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        OperationLog operlog = new OperationLog();
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            OperLog opLog = method.getAnnotation(OperLog.class);
            methodName = className + "." + methodName;
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            String params = JSON.toJSONString(rtnMap);

            operlog.setOperId(IdUtil.randomUUID());
            operlog.setOperModul(opLog.operModul());
            operlog.setOperType(opLog.operType());
            operlog.setOperDesc(opLog.operDesc());
            operlog.setOperMethod(methodName); // Request method
            operlog.setOperRequParam(params); // Request parameters
            operlog.setOperRespParam(JSON.toJSONString(keys)); // Return the result
            operlog.setOperUri(request.getRequestURI()); / / request URI
            operlog.setOperCreateTime(new Date()); // Create time

            // Prints logs
            System.out.println(JSON.toJSONString(operlog));
        } catch(Exception e) { e.printStackTrace(); }}// Convert request parameters
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    // Convert the exception information to a string
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        returnmessage; }}Copy the code

Entity class

package com.bothsavage.entity;

import lombok.Data;

import java.util.Date;

@Data
public class OperationLog {
    private String operId;
    private String operModul;
    private String operType;
    private String operDesc;
    private String OperMethod;
    private String OperRequParam;
    private String OperRespParam;
    private String OperUserId;
    private String OperUserName;
    private String OperIp;
    private String OperUri;
    private Date OperCreateTime;
    private String OperVer;
}
Copy the code

annotation

@Target(ElementType.METHOD) METHOD is annotable at the METHOD level
@Retention(RetentionPolicy.RUNTIME) // At which stage annotations are executed
@Documented
public @interface OperLog {
    String operModul(a) default ""; // Operate the module
    String operType(a) default "";  // Operation type
    String operDesc(a) default "";  // Operation instructions
}
Copy the code

controller

@RestController
public class TestController {

    @GetMapping("/test/{testName}")
    @operlog (operModul = "test module ",operType = "test",operDesc = "This is for testing ")
    public String test(@PathVariable String testName){
        return  "hello"+testName; }}Copy the code

reference

[1]. Put yourself out of your depth, implement a permission verification with AOP in SpringBoot…

[2].Spring AOP implements functional permission verification function

[3].SpringAop implements permission verification and log printing

[4]. Access control based on Spring AOP

[5]. Use SpringBoot AOP to record operation logs and exception logs

By Both Savage

This paper links: bothsavage. Making. IO / 2020/12/29 /…

Copyright Notice: All articles on this blog are licensed BY-NC-SA unless otherwise stated. Reprint please indicate the source!