RequireAuth 注解:
import java.lang.annotation.*;
/**
* @author zjy
* 请求的方法或者类上面加此注解会做权限拦截 参考AuthAspect
*
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequireAuth {
boolean require() default true;
}
注解处理:(切面)
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author zjy
* 权限拦截
* 注意:类已加上权限注解@RequireAuth的情况下,方法上的注解@RequireAuth(require = false)不会生效,
* 建议单独弄一个controller放不需要权限的请求处理方法:
* 指定别名防止controller name冲突 @RequestMapping(path = "/user", name = "noAuthUserController")
*/
@Aspect
@Slf4j
@Component
@Order(1) //切面执行优先级,越低执行优先级越高
public class AuthAspect {
/**
* 定义切点,这是一个标记方法
* com.xxx.controller下的所有子包及方法
*/
@Pointcut("execution( * com.xxx.controller..*.*(..))")
public void anyMethod() {
}
@Around("anyMethod()")
public Object auth(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
Class clazz = joinPoint.getTarget().getClass();
//类注解 优先
RequireAuth annotation = (RequireAuth) clazz.getAnnotation(RequireAuth.class);
if (annotation == null) {
//方法注解
Method method = getMethodByJointPoint(joinPoint);
annotation = method.getAnnotation(RequireAuth.class);
}
if (annotation != null && annotation.require()) {
//获取到注解且注解要求auth,开始拦截
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String action = request.getMethod();
String uri = request.getRequestURI();
log.info("action:[{}],uri:[{}]",action,uri);
//处理自己的业务逻辑,登录状态拦截或者日志打印等等
if(uri.equals("exception")){
//主动抛出异常不再往下执行方法
throw new RuntimeException("拦截啦");
}
}
//执行方法
Result result = null;
try {
result = (Result) joinPoint.proceed();
return result;
} catch (Throwable throwable) {
log.error("执行方法出错:[{}],[{}]", joinPoint.getSignature().getName(), throwable.getMessage());
throw new RuntimeException("方法执行失败");
}
}
//获取方法
private Method getMethodByJointPoint(JoinPoint joinPoint) {
Class clazz = joinPoint.getTarget().getClass();
String methodName = joinPoint.getSignature().getName();
Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();
try {
Method method = clazz.getMethod(methodName, parameterTypes);
return method;
} catch (NoSuchMethodException e) {
throw new RuntimeException("方法执行失败");
}
}
}