1、创建注解
import org.springframework.core.annotation.Order;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 操作权限注解
* 可放到方法上,也可放到类上
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Order(3)
public @interface ActionRoles {
String[] value();
}
2、在需要鉴权接口上添加直接
@PostMapping("test")
@ActionRoles(RoleType.ROLE_ADMIN)
public BiResponseDTO<String> test() {
return BiResponseDTO.success();
}
3、创建AuthorizeAspect方法
@Slf4j
@Aspect
@Component
public class RoleAuthorizeAspect {
@Around("@annotation(ActionRoles) || @within(ActionRoles)")
public Object around(ProceedingJoinPoint point) throws Throwable {
ActionRoles annotation = point.getTarget().getClass().getAnnotation(ActionRoles.class);
if(annotation != null){
checkRole(annotation.value());
return point.proceed();
}
//获取连接点
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
//获取方法ActionRoles注解
annotation = method.getAnnotation(ActionRoles.class);
if (annotation == null) {
return point.proceed();
}
checkRole(annotation.value());
return point.proceed();
}
private boolean checkRole(String[] roles) throws BaseException {
// 获取用户权限,与注解权限进行比较判断
List<String> permissionList = user.getPermissionList();
if(!ObjectUtil.isEmpty(roles) && ObjectUtil.isEmpty(permissionList)){
log.warn("当前登录账号:{}不具备权限:{},鉴权失败");
return false;
}
return true;
}
}