All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.bestwu.api.sign.ApiSignAspect Maven / Gradle / Ivy

package cn.bestwu.api.sign;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 签名验证切面
 *
 * @author Peter Wu
 */
@Slf4j
@Aspect
public class ApiSignAspect {

	@Autowired(required = false)
	private HttpServletRequest request;
	@Autowired
	private ApiSignAdpter apiSignAdpter;

	/**
	 * 管理员是否不验证,直接通过
	 */
	private boolean skipAdmin = true;
	/**
	 * 签名方式,请求参数/请求头
	 */
	private SignMode signMode = SignMode.REQUEST_HEADER;
	/**
	 * 签名参数名
	 */
	private String signParameter = "sign";

	public void setSignParameter(String signParameter) {
		this.signParameter = signParameter;
	}

	public void setSignMode(SignMode signMode) {
		this.signMode = signMode;
	}

	public void setSkipAdmin(boolean skipAdmin) {
		this.skipAdmin = skipAdmin;
	}

	/**
	 * 验证
	 */
	@Before(value = "(!@annotation(cn.bestwu.api.sign.NoApiSign)&&!@within(cn.bestwu.api.sign.NoApiSign))&&(@annotation(cn.bestwu.api.sign.ApiSign)||@within(cn.bestwu.api.sign.ApiSign))&&@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	public void verify() {
		String sign = null;
		switch (signMode) {
		case REQUEST_HEADER:
			sign = request.getHeader(this.signParameter);
			break;
		case REQUEST_BODY:
			sign = request.getParameter(this.signParameter);
			break;
		}

		if (!apiSignAdpter.isSign(request.getParameterMap(), sign, skipAdmin)) {
			RequestContextHolder.getRequestAttributes().setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, HttpStatus.BAD_REQUEST.value(), RequestAttributes.SCOPE_REQUEST);
			String msg = "invalid_request";
			RequestContextHolder.getRequestAttributes().setAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE, msg, RequestAttributes.SCOPE_REQUEST);
			InvalidRequestException invalid_request = new InvalidRequestException(msg);
			RequestContextHolder.getRequestAttributes().setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, invalid_request, RequestAttributes.SCOPE_REQUEST);
			throw invalid_request;
		} else if (log.isDebugEnabled()) {
			log.debug("sign check pass");
		}
	}

	/**
	 * 签名方式
	 *
	 * @author Peter Wu
	 */
	public enum SignMode {
		/**
		 * 请求头
		 */
		REQUEST_HEADER,
		/**
		 * 请求内容,参数方式,request_body
		 */
		REQUEST_BODY
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy