自定义标签
/**
* 对外开发接口鉴权
* @author cam
* @date 2021/11/3 13:48
*/
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authentication {
String value() default "";
}
切面环绕方法实现
import com.iris.core.tool.api.Result;
import com.iris.core.tool.utils.ObjectUtil;
import com.iris.core.tool.utils.StringUtil;
import com.iris.core.tool.utils.WebUtil;
import com.iris.sync.service.ISyncSecretService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.reflect.MethodSignature;
import java.util.HashMap;
import java.util.Map;
/**
* AOP切面(Authentication切面实现)
* @author cam
* @date 2021/11/3 13:53
*/
@Aspect
@Component
public class AuthenticationAspect {
@Autowired
private ISyncSecretService secretService;
@Around(value = "@annotation(com.iris.sync.constant.Authentication)")
public Object doBefore(ProceedingJoinPoint joinPoint) {
try {
//获取请求接口的服务器ip
String ip = WebUtil.getIP(WebUtil.getRequest());
if (StringUtil.isEmpty(ip)){
return Result.fail(SyncResult.PARAM_MISS);
}
//获取拦截的方法名
Signature sig = joinPoint.getSignature();
//获取拦截的方法名
MethodSignature methodSignature = (MethodSignature) sig;
//获取注解上的参数
Authentication authentication = methodSignature.getMethod().getDeclaredAnnotation(Authentication.class);
//请求路径
String path = authentication.value();
//获取参数
Map<String, Object> fieldsName = getFieldsName(joinPoint);
//鉴权方法
Map<String, String> checkMap = secretService.checkPermissions(ip, fieldsName.get("appId").toString(), fieldsName.get("appSecret").toString());
String isCheck= checkMap.get("success");
//鉴权失败
if (!ObjectUtil.nullSafeEquals(isCheck,"true")){
return Result.fail(SyncResult.KEY_ERROR);
}
return joinPoint.proceed();
}catch (Throwable throwable){
return Result.fail("系统出现错误");
}
}
/**
* 请求接口参数名及参数值封装成map
* @param joinPoint
* @return
*/
private static Map<String, Object> getFieldsName(ProceedingJoinPoint joinPoint) {
//参数值
Object[] args = joinPoint.getArgs();
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//参数名
String[] parameterNames = methodSignature.getParameterNames();
Map<String, Object> paramMap = new HashMap<>(32);
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
}
return paramMap;
}
}
使用
web工具类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.iris.core.tool.utils;
import com.iris.core.tool.func.Func;
import com.iris.core.tool.jackson.JsonUtil;
import com.iris.core.tool.support.Charsets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Objects;
import java.util.function.Predicate;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.util.WebUtils;
public class WebUtil extends WebUtils {
private static final Logger log = LoggerFactory.getLogger(WebUtil.class);
public static final String USER_AGENT_HEADER = "user-agent";
private static final String[] IP_HEADER_NAMES = new String[]{"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
private static final Predicate<String> IP_PREDICATE = (ip) -> {
return StringUtil.isBlank(ip) || "unknown".equalsIgnoreCase(ip);
};
public WebUtil() {
}
public static boolean isBody(HandlerMethod handlerMethod) {
ResponseBody responseBody = (ResponseBody)ClassUtil.getAnnotation(handlerMethod, ResponseBody.class);
return responseBody != null;
}
@Nullable
public static String getCookieVal(String name) {
HttpServletRequest request = getRequest();
Assert.notNull(request, "request from RequestContextHolder is null");
return getCookieVal(request, name);
}
@Nullable
public static String getCookieVal(HttpServletRequest request, String name) {
Cookie cookie = getCookie(request, name);
return cookie != null ? cookie.getValue() : null;
}
public static void removeCookie(HttpServletResponse response, String key) {
setCookie(response, key, (String)null, 0);
}
public static void setCookie(HttpServletResponse response, String name, @Nullable String value, int maxAgeInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAgeInSeconds);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
public static HttpServletRequest getRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return requestAttributes == null ? null : ((ServletRequestAttributes)requestAttributes).getRequest();
}
public static HttpServletResponse getResponse() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return requestAttributes == null ? null : ((ServletRequestAttributes)requestAttributes).getResponse();
}
public static void renderJson(HttpServletResponse response, Object result) {
renderJson(response, result, "application/json;charset=UTF-8");
}
public static void renderJson(HttpServletResponse response, Object result, String contentType) {
response.setCharacterEncoding("UTF-8");
response.setContentType(contentType);
try {
PrintWriter out = response.getWriter();
try {
out.append(JsonUtil.toJson(result));
} catch (Throwable var7) {
if (out != null) {
try {
out.close();
} catch (Throwable var6) {
var7.addSuppressed(var6);
}
}
throw var7;
}
if (out != null) {
out.close();
}
} catch (IOException var8) {
log.error(var8.getMessage(), var8);
}
}
public static String getIP() {
return getIP(getRequest());
}
@Nullable
public static String getIP(@Nullable HttpServletRequest request) {
if (request == null) {
return "";
} else {
String ip = null;
String[] var2 = IP_HEADER_NAMES;
int var3 = var2.length;
for(int var4 = 0; var4 < var3; ++var4) {
String ipHeader = var2[var4];
ip = request.getHeader(ipHeader);
if (!IP_PREDICATE.test(ip)) {
break;
}
}
if (IP_PREDICATE.test(ip)) {
ip = request.getRemoteAddr();
}
return StringUtil.isBlank(ip) ? null : StringUtil.splitTrim(ip, ",")[0];
}
}
public static String getHeader(String name) {
HttpServletRequest request = getRequest();
return ((HttpServletRequest)Objects.requireNonNull(request)).getHeader(name);
}
public static Enumeration<String> getHeaders(String name) {
HttpServletRequest request = getRequest();
return ((HttpServletRequest)Objects.requireNonNull(request)).getHeaders(name);
}
public static Enumeration<String> getHeaderNames() {
HttpServletRequest request = getRequest();
return ((HttpServletRequest)Objects.requireNonNull(request)).getHeaderNames();
}
public static String getParameter(String name) {
HttpServletRequest request = getRequest();
return ((HttpServletRequest)Objects.requireNonNull(request)).getParameter(name);
}
public static String getAllParameter(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
Enumeration parameterNames = request.getParameterNames();
String bodyStr;
while(parameterNames.hasMoreElements()) {
bodyStr = (String)parameterNames.nextElement();
String value = request.getParameter(bodyStr);
StringUtil.appendBuilder(sb, new CharSequence[]{bodyStr, "=", value, "&"});
}
bodyStr = "";
String str;
try {
for(BufferedReader br = request.getReader(); (str = br.readLine()) != null; bodyStr = bodyStr + str) {
}
} catch (IOException var6) {
log.error("RequestBody参数解析失败", var6);
}
if (StringUtil.isNotBlank(bodyStr)) {
StringUtil.appendBuilder(sb, new CharSequence[]{" ", "RequestBody= ", bodyStr});
}
str = StringUtil.removeSuffix(sb.toString(), "&");
return str.replaceAll("&", "&");
}
public static String getRequestBody(ServletInputStream servletInputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(servletInputStream, StandardCharsets.UTF_8));
String line;
while((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException var16) {
log.error("获取 request 请求体失败", var16);
} finally {
if (servletInputStream != null) {
try {
servletInputStream.close();
} catch (IOException var15) {
var15.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException var14) {
var14.printStackTrace();
}
}
}
return sb.toString();
}
public static String getRequestContent(HttpServletRequest request) {
try {
String queryString = request.getQueryString();
if (StringUtil.isNotBlank(queryString)) {
return (new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8)).replaceAll("&", "&").replaceAll("%22", "\"");
} else {
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
byte[] buffer = getRequestBody(request.getInputStream()).getBytes();
String str = (new String(buffer, charEncoding)).trim();
if (StringUtil.isBlank(str)) {
StringBuilder sb = new StringBuilder();
Enumeration parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()) {
String key = (String)parameterNames.nextElement();
String value = request.getParameter(key);
StringUtil.appendBuilder(sb, new CharSequence[]{key, "=", value, "&"});
}
str = StringUtil.removeSuffix(sb.toString(), "&");
}
return str.replaceAll("&", "&");
}
} catch (Exception var9) {
var9.printStackTrace();
return "";
}
}
public static boolean internalIp(String ip) {
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
private static boolean internalIp(byte[] addr) {
if (!Func.isNull(addr) && addr.length >= 2) {
byte b0 = addr[0];
byte b1 = addr[1];
byte SECTION_1 = true;
byte SECTION_2 = true;
byte SECTION_3 = true;
byte SECTION_4 = true;
byte SECTION_5 = true;
byte SECTION_6 = true;
switch(b0) {
case -84:
if (b1 >= 16 && b1 <= 31) {
return true;
}
case -64:
switch(b1) {
case -88:
return true;
}
default:
return false;
case 10:
return true;
}
} else {
return true;
}
}
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
} else {
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try {
long l;
int i;
switch(elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if (l < 0L || l > 4294967295L) {
return null;
}
bytes[0] = (byte)((int)(l >> 24 & 255L));
bytes[1] = (byte)((int)((l & 16777215L) >> 16 & 255L));
bytes[2] = (byte)((int)((l & 65535L) >> 8 & 255L));
bytes[3] = (byte)((int)(l & 255L));
break;
case 2:
l = (long)Integer.parseInt(elements[0]);
if (l >= 0L && l <= 255L) {
bytes[0] = (byte)((int)(l & 255L));
l = (long)Integer.parseInt(elements[1]);
if (l < 0L || l > 16777215L) {
return null;
}
bytes[1] = (byte)((int)(l >> 16 & 255L));
bytes[2] = (byte)((int)((l & 65535L) >> 8 & 255L));
bytes[3] = (byte)((int)(l & 255L));
break;
}
return null;
case 3:
for(i = 0; i < 2; ++i) {
l = (long)Integer.parseInt(elements[i]);
if (l < 0L || l > 255L) {
return null;
}
bytes[i] = (byte)((int)(l & 255L));
}
l = (long)Integer.parseInt(elements[2]);
if (l < 0L || l > 65535L) {
return null;
}
bytes[2] = (byte)((int)(l >> 8 & 255L));
bytes[3] = (byte)((int)(l & 255L));
break;
case 4:
for(i = 0; i < 4; ++i) {
l = (long)Integer.parseInt(elements[i]);
if (l < 0L || l > 255L) {
return null;
}
bytes[i] = (byte)((int)(l & 255L));
}
return bytes;
default:
return null;
}
return bytes;
} catch (NumberFormatException var6) {
return null;
}
}
}
}