AOP自定义注解鉴权

刚出来工作那会或者在学校的时候,经常听到说AOP(面向对象编程,熟称切面)的用途是日志、鉴权等。但是那会不会,后面学会了,又没有写博客记录,今天写给大伙,希望能帮到大家

 

一、学习目标:利用AOP+自定义注解进行权限拦截并校验

       下面开始进入正题,引入aop依赖

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

 

二:首先自定义注解的创建

 


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target (ElementType.METHOD) //这个注解的作用,大家自定搜,我记得我的博客也有记录,这里的意思是该自定义注解作用在方法上
@Retention (RetentionPolicy.RUNTIME)
public @interface Auth
{
Type type() default Type.BASE;

// 鉴权类型,如果大伙的项目没有区分鉴权类型,此处的代码可以忽略
enum Type
{
// 鉴权方式一(看自身的业务需求,此值是客户端的鉴权方式)
BASE,
// 鉴权方式二(看自身的业务需求,此值是后台管理员的鉴权方式)
ADMIN
}
}
 

 

三、编写AOP类:AopAuth.class


import lombok.extern.slf4j.Slf4j;
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;

@Slf4j @Aspect @Order(
1) @Component
public class AopAuth {
@Autowire
private HttpServletRequest request;
/** * 配置切入点:注意,这里的注解@annotation里面是上面的自定义注解类所在的全包名路径 */ @Pointcut("@annotation(com.xxxx.xxxx.xxxx.annotation.Auth)") public void pointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } @Before("pointcut() && @annotation(auth)") public void before(JoinPoint joinPoint, Auth auth) throws Exception { if (Auth.Type.BASE.equals(auth.type())) { String token = request.getHeader("Authorization"); //这里是从前端的请求头里面获取对应的token //token鉴权(自己的业务系统根据什么方式来解密自己才知道):此处鉴权token自行根据自己的业务去编写,小编也不能帮大伙了 } } }

 

posted @ 2022-02-08 11:44  QH.Thomas  阅读(569)  评论(0编辑  收藏  举报