|
|
@@ -0,0 +1,60 @@
|
|
|
+package cn.seecoder.data.server.utils.aspects.auth;
|
|
|
+
|
|
|
+import cn.hutool.core.util.StrUtil;
|
|
|
+import cn.seecoder.data.server.utils.enums.ErrorCodeEnum;
|
|
|
+import cn.seecoder.data.server.utils.enums.UserRole;
|
|
|
+import cn.seecoder.data.server.utils.exception.GlobalException;
|
|
|
+import com.auth0.jwt.JWT;
|
|
|
+import com.auth0.jwt.algorithms.Algorithm;
|
|
|
+import com.auth0.jwt.exceptions.JWTVerificationException;
|
|
|
+import com.auth0.jwt.interfaces.DecodedJWT;
|
|
|
+import com.auth0.jwt.interfaces.JWTVerifier;
|
|
|
+import org.aspectj.lang.JoinPoint;
|
|
|
+import org.aspectj.lang.annotation.Aspect;
|
|
|
+import org.aspectj.lang.annotation.Before;
|
|
|
+import org.springframework.beans.BeanUtils;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.core.annotation.Order;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.web.context.request.RequestContextHolder;
|
|
|
+import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
+
|
|
|
+import javax.servlet.http.HttpServletRequest;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Objects;
|
|
|
+import java.util.Optional;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+@Aspect
|
|
|
+@Component
|
|
|
+@Order(1)
|
|
|
+public class AuthHandlerAspectJ {
|
|
|
+ @Value("${jwt.secret}")
|
|
|
+ private String jwtSecret;
|
|
|
+
|
|
|
+ @Before("execution(public * cn.seecoder.data.server.controller.*.*(..)) && @annotation(auth)")
|
|
|
+ public void authCheck(JoinPoint joinPoint, Auth auth) {
|
|
|
+ HttpServletRequest httpServletRequest =
|
|
|
+ ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
|
|
|
+ .getRequest();
|
|
|
+ String token = Optional.ofNullable(httpServletRequest.getHeader("Authorization"))
|
|
|
+ .orElseThrow(() -> new GlobalException(ErrorCodeEnum.USER_ERROR_A0001));
|
|
|
+
|
|
|
+ JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
|
|
|
+
|
|
|
+ DecodedJWT decodedJWT;
|
|
|
+
|
|
|
+ try {
|
|
|
+ decodedJWT = jwtVerifier.verify(token);
|
|
|
+ } catch (JWTVerificationException e) {
|
|
|
+ throw new GlobalException(ErrorCodeEnum.USER_ERROR_A0002);
|
|
|
+ }
|
|
|
+
|
|
|
+ UserInfo userInfo = decodedJWT.getClaim("user_info").as(UserInfo.class);
|
|
|
+
|
|
|
+ for (UserRole role : auth.roles()) {
|
|
|
+ if (role == userInfo.getRole()) return;
|
|
|
+ }
|
|
|
+ throw new GlobalException(ErrorCodeEnum.USER_ERROR_A0003);
|
|
|
+ }
|
|
|
+}
|