Api接⼝鉴权注解实现考研政治参考书
定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiHeaderCheck {
}
定义切⾯
@Aspect
@Component
@Slf4j
public class ApiHeaderCheckAspect {
//30s超时
public static final int REQUEST_EXPIRE_TIME = 30000;
gentle是什么意思
@Before("@annotation(apiHeaderCheck)")
public void checkAuth(ApiHeaderCheck apiHeaderCheck) {
HttpServletRequest request = currentRequest();
if (Objects.isNull(request)) {
return;
}
String timeStampStr = Header("x-ts");
String sign = Header("x-sign");torch是什么意思
if (StringUtils.isEmpty(timeStampStr) || StringUtils.isEmpty(sign)) {
没办法英文
throw new BaException(ApiAuthErrorEnum.UNAUTHORIZED);
}
String regex = "^\\d{13}$";
if (!Pattern.matches(regex, im())) {
throw new BaException(ApiAuthErrorEnum.UNAUTHORIZED);
}
long requestTimestamp = Long.parLong(timeStampStr);
if (System.currentTimeMillis() - requestTimestamp > REQUEST_EXPIRE_TIME) {
throw new BaException(ApiAuthErrorEnum.REQUEST_EXPIRED);
}
/
/验证RSA签名
String targetTimestamp = RsaUtil.decrypt(sign);
if (!targetTimestamp.equals(timeStampStr)) {
throw new BaException(ApiAuthErrorEnum.UNAUTHORIZED);毕业旅行英文
}
}
/**
* 获取当前请求信息
* @return Current request or null
aisle*/
private HttpServletRequest currentRequest() {
ServletRequestAttributes rvletRequestAttributes = (ServletRequestAttributes) RequestAttributes(); return Optional.ofNullable(rvletRequestAttributes).map(ServletRequestAttributes::getRequest).orEl(null);
}
}
定义异常
1public enum ApiAuthErrorEnum implements IErrorCode {
2
3 UNAUTHORIZED("10001", "Unauthorized"),
4 REQUEST_EXPIRED("10002", "Request Expired"),
5 ;
6
7private final String errorCode;
8private final String errorMessage;
appleton9private static final String ERROR_CODE_START = "Auth-";
10
11 ApiAuthErrorEnum(String errorCode, String errorMessage) {
14 }
15
16 @Override
血染拜占庭17public String getErrorCode() {
bec考试教材
18return ERROR_CODE_START + errorCode;
19 }
20
21 @Override
22public String getErrorMessage() {
23return errorMessage;
24 }
25 }
使⽤⽅式
在⽅法上添加@ApiHeaderCheck
add_header Access-Control-Allow-Headers 'x-sign,x-ts'; 如
location /bssgw/ {
proxy_pass 127.0.0.1:8080/test/;
proxy_t_header Host $host:$rver_port;
proxy_t_header X-Real-IP $remote_addr;
proxy_t_header REMOTE-HOST $remote_addr;
青岛it proxy_t_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header Access-Control-Allow-Headers 'x-sign,x-ts';
client_max_body_size 50m;
}