工具类:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
private static final char[] MD5_HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public MD5Util() {
}
public static String encryptionMD5(String content) throws NoSuchAlgorithmException {
byte[] strTemp = content.toString().getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for(int i = 0; i < j; ++i) {
byte b = md[i];
str[k++] = MD5_HEX_DIGITS[b >> 4 & 15];
str[k++] = MD5_HEX_DIGITS[b & 15];
}
return new String(str);
}
public static String encryptionMD5(String content, String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException {
byte[] strTemp = content.toString().getBytes(charset);
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for(int i = 0; i < j; ++i) {
byte b = md[i];
str[k++] = MD5_HEX_DIGITS[b >> 4 & 15];
str[k++] = MD5_HEX_DIGITS[b & 15];
}
return new String(str);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(encryptionMD5("4ikmlp"));
}
}
tokenUtil
import com.yuelvhui.util.exception.ServiceException;
import com.yuelvhui.util.safety.MD5Util;
import com.yuelvhui.util.string.StringUtil;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class TokenUtil {
public static boolean verifyToken(String managerId, String timeStamp, String mchKey, String token) {
String preSignStr = StringUtil.append(managerId, ".", timeStamp, ".", mchKey);
if (MD5Sign(preSignStr, token)) {
return true;
}
throw new ServiceException(ErrorCode.TokenVerificationFailure.getCode(), "请求头签名校验失败");
}
public static boolean MD5Sign(String str, String sign) {
try {
String sign2 = MD5Util.encryptionMD5(str);
System.out.println("系统加密数据"+"-----"+sign2);
System.out.println("传值加密数据"+"-----"+sign);
if (sign2.equals(sign)) {
return true;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return false;
}
public static String encryptionMD5(String content) throws NoSuchAlgorithmException {
byte[] strTemp = content.toString().getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for(int i = 0; i < j; ++i) {
byte b = md[i];
str[k++] = MD5_HEX_DIGITS[b >> 4 & 15];
str[k++] = MD5_HEX_DIGITS[b & 15];
}
return new String(str);
}
}
注解类:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SystemToken {
boolean required() default true;
}
拦截器:
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuelvhui.entity.PermissionMerchant;
import com.yuelvhui.interfaces.SystemToken;
import com.yuelvhui.mapper.PermissionMerchantMapper;
import com.yuelvhui.util.exception.ServiceException;
import com.yuelvhui.util.string.StringUtil;
import com.yuelvhui.utils.Constants;
import com.yuelvhui.utils.ErrorCode;
import com.yuelvhui.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
PermissionMerchantMapper permissionMerchantMapper;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
// 从 http 请求头中取出 token
String token = httpServletRequest.getHeader(Constants.HTTP_HEADER_AUTHORIZATION);
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(SystemToken.class)) {
SystemToken systemToken = method.getAnnotation(SystemToken.class);
if (systemToken.required()) {
// 执行认证
if (StringUtil.isBlank(token) || !token.startsWith(Constants.AUTHORIZATION_PREFIX_SYS)) {
throw new ServiceException(ErrorCode.TokenVerificationFailure.getCode(), "无请求头或请求头签名校验失败");
}
//截取到用户的token
token = token.substring(Constants.AUTHORIZATION_PREFIX_SYS.length()).toLowerCase();
try {
String[] params = token.split("\\.");
PermissionMerchant merchant = permissionMerchantMapper.selectOne(new LambdaQueryWrapper<PermissionMerchant>().eq(PermissionMerchant::getMchId, params[0]));
System.out.println("密钥"+"-----"+merchant.getMchKey());
if (ObjectUtils.isEmpty(merchant)) {
throw new ServiceException(ErrorCode.NotFoundData.getCode(), "Token校验失败");
}
//校验签名
return TokenUtil.verifyToken(params[0], params[1], merchant.getMchKey(), params[2]);
}catch (Exception e){
throw new ServiceException(ErrorCode.TokenVerificationFailure.getCode(),"Token信息验证失败");
}
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}