面向切圖編程示例

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();
    }
}


發佈了40 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章