SignAspect.java 3.01 KB
package com.xkl.authorization.aspect;

import com.xkl.repository.XklInterKeyRespository;
import com.xkl.security.SecurityTool;
import com.xkl.tools.UtilTools;
import lombok.extern.apachecommons.CommonsLog;
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.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by win7 on 2016/11/20.
 *加密算法:
 * t: 北京时间距离1970年1月1日的秒数
 * key:(平台对应的key,此值喜开路管理员授予)
 * str:业务参数数组,按参数名递增排序排列拼接,例如用户登陆接口,coid+password+username
 * sign=md5(str+t+key),32位小写md5
 * 需要验证:
 * sign:是否正确
 * t:是否过期,客户端与服务器时间必须为±300s以内,否则时间验证过期。
 */
@Service
@Aspect
@CommonsLog
public class SignAspect {
    @Autowired
    private XklInterKeyRespository xklInterKeyRespository;

    /**
     * 由接口传过来的type获取xkl_inter_key表中的key
     * @param type
     * @return
     */
    private String getKeyByType(int type){
        long id = 0;
        if(type == 1)
            id = 1;
        else
            id = 2;
        return (xklInterKeyRespository.findOne(id) == null)?"":xklInterKeyRespository.findOne(id).getKey();
    }
    /**
     * 定义切点,定位到@Sign注解的地方
     */
    @Pointcut("@annotation(com.xkl.authorization.annotation.Sign)")
    public void signPointCut() {

    }

    @Before(value="signPointCut()")
    public void beforeSign(JoinPoint joinPoint) throws Exception {
        Object[] args = joinPoint.getArgs();

        //Controller中所有方法的参数,前两个分别为:Request,Response
        HttpServletRequest request = (HttpServletRequest) args[0];
        // HttpServletResponse response = (HttpServletResponse)args[1];
        String sign = request.getParameter("sign");
        long t = UtilTools._long(request.getParameter("t"));
        int type = UtilTools._int(request.getParameter("type"));

        /**
         * str为
         * sign=md5(str+t+key)
         */
        Map<String,String[]> map=request.getParameterMap();
        List<String> list=Collections.list(request.getParameterNames());
        Collections.sort(list);
        String str="";
        for(String para:list){
            if(!para.equals("sign")&&!para.equals("t")&&!para.equals("type"))
                str += map.get(para)[0];
        }

        String key = getKeyByType(type);
        long t1= UtilTools.getNow10Second();
        String sign1= SecurityTool.encode("MD5",str+t+key);
        /**
         *  比较sign和过期时间
         */
        if(sign1.equals(sign)&&Math.abs(t1-t)<300){

        }else{
            throw new Exception("您无权操作!");
        }
    }
}