SpringBoot认证token的AOP实例

1.声名注解

package com.eternalray.conf;


import java.lang.annotation.*;

/**
 * 安全认证
 * @author EternalRay
 */
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorized {
}

2.定义切面

package com.eternalray.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;

/**
 * 安全切面认证配置
 * @author EternalRay
 */
@Aspect
@Order(0)
@Component
@Slf4j
public class AuthorizedAspectConf {

    /**
     * 请求头认证字段
     */
    private static final String HEAD_AUTHORIZATION="Authorization";

    /**
     * 请求切点方法(已提供@RequestMapping,@GetMapping,@PostMapping注解,需要其它请增加)
     */
    @Pointcut(" @annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
            "   @annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "   @annotation(org.springframework.web.bind.annotation.PostMapping)")
    void requestMapping() {
    }

    /**
     * 范围切点方法
     */
    @Pointcut("execution(* com.eternalray.controller.*.*(..))")
    public void methodPointCut() {
    }

    /**
     * 某个方法执行前进行请求合法性认证 注入Authorized注解 (先)
     */
    @Before("requestMapping() && methodPointCut() && @annotation(authorized)")
    void doBefore(JoinPoint joinPoint, Authorized authorized) throws Exception{
        Class type = joinPoint.getSignature().getDeclaringType();
        Annotation[] annotations = type.getAnnotationsByType(Authorized.class);
        if (ObjectUtils.isEmpty(annotations)) {
            log.info("进入AOP方法认证...");
            authLogic(joinPoint);
        }
    }
    /**
     * 类下面的所有方法执行前进行请求合法性认证 (后)
     */
    @Before("requestMapping() && methodPointCut()")
    void doBefore(JoinPoint joinPoint) throws Exception {
        Class type = joinPoint.getSignature().getDeclaringType();
        Annotation[] annotations = type.getAnnotationsByType(Authorized.class);
        if (!ObjectUtils.isEmpty(annotations)) {
            log.info("进入AOP类认证...");
            authLogic(joinPoint);
        }
    }

    /**
     * 认证逻辑
     * @param joinPoint
     * @throws Exception
     */
    private void authLogic(JoinPoint joinPoint) throws Exception {
        log.info("认证开始...");
        String classType = joinPoint.getTarget().getClass().getName();
        Class clazz = Class.forName(classType);
        String clazzName = clazz.getName();
        String methodName = joinPoint.getSignature().getName();
        log.info("ClassName: "+clazzName);
        log.info("MethodName:"+methodName);
        //获取当前http请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader(HEAD_AUTHORIZATION);
        if(StringUtils.isNotEmpty(token)){
            log.debug("请求认证通过!");
        }else {
            throw new Exception("请求被拒绝!");
        }
    }
}

3.控制层

package com.eternalray.controller;


import com.eternalray.conf.Authorized;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;



/**
 * Authorized注解作用在类上时该类所有方法将进行AOP
 * Authorized注解作用在方法时将对方法进行AOP
 * 二者同时存在不会重复执行AOP,将会执行AOP类认证
 */

/**
 * @author EternalRay
 */
@Authorized
@RestController
public class TestController {

    @Authorized
    @GetMapping("/get")
    Object get(){
        Map map = new HashMap<>(1);
        map.put("get","getValue");
        return map;
    }

    @PostMapping("/get2")
    Object get2(){
        Map map = new HashMap<>(1);
        map.put("get2","get2Value");
        return map;
    }

}

4.完整POM



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.8.RELEASE
         
    
    com.eternalray
    aop
    1.0
    aop
    AOP

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
        

        
            org.apache.commons
            commons-lang3
        

        
            org.aspectj
            aspectjweaver
        


    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


5.全局异常捕获

全局异常类代码链接

 

注:该文参考以下链接后进行内容原创

参考链接:https://www.cnblogs.com/jeffwongishandsome/archive/2018/06/08/9090374.html

你可能感兴趣的:(Java,IDEA,SpringBoot)