使用AOP实现登陆拦截,校验用户是否合法以及校验用户的身份。
自定义注解
自定义注解 LoginValidator,放在com.swx.easypan.annotation
包下,有些接口不需要拦截。
LoginValidator@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LoginValidator { boolean validated() default true;
boolean checkAdmin() default false; }
|
AOP拦截
使用AOP拦截加了 LoginValidator 注解的接口,放在com.swx.easypan.aspect
包下
- 从请求中获取Session,再从Session中获取用户信息,如果失败则没有登陆
- 如果有用户信息,判断该接口注解是否需要管理员权限
@Aspect @Component public class LoginAspect {
@Pointcut("@annotation(com.swx.easypan.annotation.LoginValidator) || @within(com.swx.easypan.annotation.LoginValidator)") private void pointCut() {}
@Before("pointCut()") public void interceptorDo(JoinPoint point) { Object target = point.getTarget(); MethodSignature methodSignature = (MethodSignature) point.getSignature(); Method method = methodSignature.getMethod(); LoginValidator loginValidator = method.getAnnotation(LoginValidator.class); if (loginValidator !=null && !loginValidator.validated()) { return; } ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); if (requestAttributes == null || requestAttributes.getResponse() == null) { return; } HttpServletRequest request = requestAttributes.getRequest(); HttpSession session = request.getSession(); SessionWebUserVO userVo = (SessionWebUserVO) session.getAttribute(Constants.SESSION_KEY); if (null == userVo) { throw new BizException(ResultCode.LOGIN_AUTH_FAIL); } if (loginValidator != null && loginValidator.checkAdmin() && !userVo.getIsAdmin()) { throw new BizException(ResultCode.NO_PERMISSION); } } }
|