本文将通过AOP的方式实现一个相对更加简易灵活的API安全认证服务。
我们先看实现,然后介绍和分析AOP基本原理和常用术语。
一、Authorized实现
1、定义注解
package com.power.demo.common;
import java.lang.annotation.*;
/*
* 安全认证
* */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorized {
String value() default "";
}
这个注解看上去什么都没有,仅仅是一个占位符,用于标志是否需要安全认证。
2、表现层使用注解
@Authorized
@RequestMapping(value = "/getinfobyid", method = RequestMethod.POST)
@ApiOperation("根据商品Id查询商品信息")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "authtoken", required = true, value = "authtoken", dataType =
"String"),
})
public GetGoodsByGoodsIdResponse getGoodsByGoodsId(@RequestHeader String authtoken, @RequestBody GetGoodsByGoodsIdRequest request) {
return _goodsApiService.getGoodsByGoodsId(request);
}
看上去就是在一个方法上加了Authorized注解,其实它也可以作用于类上,也可以类和方法混合使用。
3、请求认证切面
下面的代码是实现灵活的安全认证的关键:
package com.power.demo.controller.tool;
import com.power.demo.common.AppConst;
import com.power.demo.common.Authorized;
import com.power.demo.common.BizResult;
import com.power.demo.service.contract.AuthTokenService;
import com.power.demo.util.PowerLogger;
import com.power.demo.util.SerializeUtil;
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.beans.factory.annotation.Autowired;
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.annotation.Annotation;
/**
* 请求认证切面,验证自定义请求header的authtoken是否合法
**/
@Aspect
@Component
public class AuthorizedAspect {
@Autowired
private AuthTokenService authTokenService;
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void requestMapping() {
}
@Pointcut("execution(* com.power.demo.controller.*Controller.*(..))")
public void methodPointCut() {
}
/**
* 某个方法执行前进行请求合法性认证 注入Authorized注解 (先)
*/
@Before("requestMapping() && methodPointCut()&&@annotation(authorized)")
public void doBefore(JoinPoint joinPoint, Authorized authorized) throws Exception {
PowerLogger.info("方法认证开始...");
Class type = joinPoint.getSignature().getDeclaringType();
Annotation[] annotations = type.getAnnotationsByType(Authorized.class);
if (annotations != null && annotations.length > 0) {
PowerLogger.info("直接类认证");
return;
}
//获取当前http请求
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader(AppConst.AUTH_TOKEN);
BizResult<String> bizResult = authTokenService.powerCheck(token);
System.out.println(SerializeUtil.Serialize(bizResult));
if (bizResult.getIsOK() == true) {
PowerLogger.info("方法认证通过");
} else {
throw new Exception(bizResult.getMessage());
}
}
/**
* 类下面的所有方法执行前进行请求合法性认证 (后)
*/
@Before("requestMapping() && methodPointCut()")
public void doBefore(JoinPoint joinPoint) throws Exception {
PowerLogger.info("类认证开始...");
Annotation[] annotations = joinPoint.getSignature().getDeclaring