import com.xx.common.utils.system.exception.exceptions.TokenException; import com.xx.common.utils.system.security.annotation.IgnoreSecurity; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; /** * SecurityAspect * * @author Dengzw * @date 16/9/28 */ @Aspect public class SecurityAspect { private static final String DEFAULT_TOKEN_NAME = "X-Token"; private Logger logger = LoggerFactory.getLogger(SecurityAspect.class); /*初始化默认值*/ private TokenManager tokenManager = new DefaultTokenManager(); private String tokenName = DEFAULT_TOKEN_NAME; public void setTokenManager(TokenManager tokenManager) { this.tokenManager = tokenManager; } public void setTokenName(String tokenName) { if (tokenName == null||tokenName.trim().equals("")) { tokenName = DEFAULT_TOKEN_NAME; } this.tokenName = tokenName; } /** * TODO 标注切点位置,注:此方法中的内容不会被执行,只起标识作用 */ @Pointcut("execution(* com.xxxx.xxx.manager.controller..*.*(..))") public void checkToken(){} @Around("checkToken()") public Object execute(ProceedingJoinPoint pjp) throws TokenException,Throwable { /*从切点上获取目标方法*/ MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); /*若目标方法忽略了安全性检查,则直接调用目标方法*/ if (method.isAnnotationPresent(IgnoreSecurity.class)) { return pjp.proceed(); } /*从 request header 中获取当前 token*/ RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String token = request.getHeader(tokenName); logger.info("*****Request Token:"+token); /*检查 token 有效性*/ if (!tokenManager.checkToken(token)) { String message = String.format("token [%s] is invalid", token); throw new TokenException(message); } /*调用目标方法*/ return pjp.proceed(); } }