Prechádzať zdrojové kódy

检测请求携带的 cookie, 判断请求是否认证

reghao 2 rokov pred
rodič
commit
f6f2fa4a75

+ 4 - 0
dfs-store/pom.xml

@@ -87,6 +87,10 @@
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-validation</artifactId>

+ 11 - 0
dfs-store/src/main/java/cn/reghao/dfs/store/auth/AuthException.java

@@ -0,0 +1,11 @@
+package cn.reghao.dfs.store.auth;
+
+/**
+ * @author reghao
+ * @date 2023-07-18 15:25:00
+ */
+public class AuthException extends Throwable {
+    public AuthException(String msg) {
+        super(msg);
+    }
+}

+ 14 - 0
dfs-store/src/main/java/cn/reghao/dfs/store/auth/AuthUser.java

@@ -0,0 +1,14 @@
+package cn.reghao.dfs.store.auth;
+
+import java.lang.annotation.*;
+
+/**
+ * @author reghao
+ * @date 2023-07-18 15:15:10
+ */
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface AuthUser {
+    boolean value() default true;
+}

+ 59 - 0
dfs-store/src/main/java/cn/reghao/dfs/store/auth/AuthUserAspect.java

@@ -0,0 +1,59 @@
+package cn.reghao.dfs.store.auth;
+
+import cn.reghao.dfs.store.util.UserContext;
+import cn.reghao.jutil.web.ServletUtil;
+import cn.reghao.tnb.account.api.constant.TokenType;
+import cn.reghao.tnb.account.api.dto.AccountInfo;
+import cn.reghao.tnb.account.api.iface.AuthService;
+import org.apache.dubbo.config.annotation.DubboReference;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+
+/**
+ * @author reghao
+ * @date 2023-07-18 15:17:35
+ */
+@Component
+@Aspect
+public class AuthUserAspect {
+    @DubboReference(check = false)
+    private AuthService authService;
+    private final String cookieKey = "USERDATA";
+
+    @Pointcut("@annotation(cn.reghao.dfs.store.auth.AuthUser)")
+    public void loginPointCut(){
+    }
+
+    @Around("loginPointCut()")
+    public Object tokenHandler(ProceedingJoinPoint point) throws Throwable {
+        Class<?> aClass = point.getTarget().getClass();
+        MethodSignature ms = (MethodSignature)point.getSignature();
+        Method method = aClass.getDeclaredMethod(ms.getName(),ms.getParameterTypes());
+        AuthUser authUser = method.getAnnotation(AuthUser.class);
+
+        String sessId = ServletUtil.getCookie(cookieKey);
+        AccountInfo accountInfo = null;
+        if (sessId != null) {
+            accountInfo = authService.getAccountInfo(TokenType.cookie.getValue(), sessId);
+        } else {
+            sessId = ServletUtil.getBearerToken();
+            if (sessId != null) {
+                accountInfo = authService.getAccountInfo(TokenType.token.getValue(), sessId);
+            }
+        }
+
+        boolean auth = authUser.value();
+        if (auth && accountInfo != null) {
+            UserContext userContext = new UserContext(accountInfo.getUserId());
+            return point.proceed(point.getArgs());
+        }
+
+        throw new AuthException("接口需要认证后才可访问");
+    }
+}

+ 68 - 0
dfs-store/src/main/java/cn/reghao/dfs/store/exception/ControllerExceptionHandler.java

@@ -0,0 +1,68 @@
+package cn.reghao.dfs.store.exception;
+
+import cn.reghao.dfs.store.auth.AuthException;
+import cn.reghao.jutil.jdk.exception.ExceptionUtil;
+import cn.reghao.jutil.jdk.result.WebResult;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.stream.Collectors;
+
+/**
+ * 全局异常处理类,处理 controller 抛出的异常
+ *
+ * @author reghao
+ * @date 2019/03/21 10:25:49
+ */
+@Slf4j
+@ControllerAdvice
+public class ControllerExceptionHandler {
+    /**
+     * 处理所有 controller 上抛出的异常
+     *
+     * @date 2019-09-28 上午11:01
+     */
+    @ExceptionHandler({Exception.class})
+    @ResponseBody
+    public ResponseEntity<String> error(Exception e, HttpServletRequest request) {
+        String uri = request.getRequestURI();
+        String msg = ExceptionUtil.errorMsg(e);
+        log.error("{} 接口抛出异常: {}", uri, msg);
+
+        String body = WebResult.errorWithMsg(msg);
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        int status = HttpStatus.OK.value();
+        if (e instanceof MethodArgumentNotValidException) {
+            // 参数校验失败
+            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
+            String errMsg = exception.getBindingResult().getAllErrors().stream()
+                    .map(objectError -> {
+                        String message = objectError.getDefaultMessage();
+                        return message + "\n";
+                    }).collect(Collectors.joining());
+            body = WebResult.errorWithMsg(errMsg);
+            /*body = exception.getBindingResult().getAllErrors().stream()
+                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
+                    .collect(Collectors.joining());*/
+        } else if (e instanceof IllegalStateException) {
+            IllegalStateException exception = (IllegalStateException) e;
+            Throwable throwable = exception.getCause();
+            if (throwable instanceof AuthException) {
+                status = HttpStatus.UNAUTHORIZED.value();
+            }
+
+            body = WebResult.errorWithMsg(throwable.getMessage());
+        }
+
+        return ResponseEntity.status(status).headers(headers).body(body);
+    }
+}

+ 43 - 0
dfs-store/src/main/java/cn/reghao/dfs/store/exception/FilterExceptionHandler.java

@@ -0,0 +1,43 @@
+package cn.reghao.dfs.store.exception;
+
+import cn.reghao.jutil.jdk.converter.DateTimeConverter;
+import org.springframework.boot.autoconfigure.web.ErrorProperties;
+import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
+import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 处理 filter 中抛出的异常
+ * 需要配置 server.error.path=/error
+ *
+ * @author reghao
+ * @date 2020-06-19 13:34:19
+ */
+@RestController
+public class FilterExceptionHandler extends BasicErrorController {
+    public FilterExceptionHandler() {
+        super(new DefaultErrorAttributes(), new ErrorProperties());
+    }
+
+    @Override
+    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
+    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
+        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
+        HttpStatus status = getStatus(request);
+
+        Map<String,Object> map = new HashMap<>();
+        map.put("code",body.get("status"));
+        map.put("msg",body.get("message"));
+        map.put("timestamp", DateTimeConverter.format(System.currentTimeMillis()));
+        map.put("data",body.get("data"));
+        return ResponseEntity.status(status).body(map);
+    }
+}

+ 4 - 3
dfs-store/src/main/java/cn/reghao/dfs/store/inerceptor/TokenFilter.java

@@ -23,14 +23,15 @@ public class TokenFilter implements Filter {
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
             throws IOException, ServletException {
         long userId = -1L;
-        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+        /*HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         String auth = httpServletRequest.getHeader("Authorization");
         if (auth != null) {
         }
 
         try (UserContext context = new UserContext(userId)) {
-            chain.doFilter(request, response);
-        }
+        }*/
+
+        chain.doFilter(request, response);
     }
 
     @Override