处理可以匿名访问的资源

This commit is contained in:
2023-07-30 22:49:23 +08:00
parent 369ff72754
commit b3d899e204
4 changed files with 54 additions and 5 deletions

View File

@@ -0,0 +1,19 @@
package cn.lihongjie.coal.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Anonymous {
boolean value() default true;
}

View File

@@ -1,6 +1,8 @@
package cn.lihongjie.coal.aop;
import cn.lihongjie.coal.annotation.Anonymous;
import cn.lihongjie.coal.annotation.SysLog;
import cn.lihongjie.coal.common.Ctx;
import cn.lihongjie.coal.common.RequestUtils;
import cn.lihongjie.coal.dto.R;
import cn.lihongjie.coal.entity.SysLogEntity;
@@ -30,7 +32,6 @@ import java.util.Arrays;
public class ControllerAop {
@Pointcut("execution (* cn.lihongjie.coal.controller.*.*(..))")
public void controllerMethods() {
@@ -44,6 +45,29 @@ public class ControllerAop {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 处理接口权限
if (!Ctx.isLoggedIn()) {
Anonymous anonymous = AnnotationUtils.findAnnotation(method, Anonymous.class);
if (anonymous != null && !anonymous.value()) {
return R.fail("invalidToken", "登录状态失效,请重新登录");
}
Anonymous clsAnonymous = AnnotationUtils.findAnnotation(method.getClass(), Anonymous.class);
if (clsAnonymous == null || !clsAnonymous.value()) {
return R.fail("invalidToken", "登录状态失效,请重新登录");
}
}
long start = System.currentTimeMillis();
SysLogEntity sysLogEntity = createSysLog(method, request);
try {
@@ -54,7 +78,6 @@ public class ControllerAop {
} catch (Throwable e) {
logException(e, proceedingJoinPoint);
@@ -71,8 +94,6 @@ public class ControllerAop {
}
} finally {

View File

@@ -15,6 +15,11 @@ public class Ctx {
}
public static boolean isLoggedIn(){
return getAuthentication() != null && getAuthentication().isAuthenticated();
}
public static String getSessionId(){
return getAuthentication().getSessionId();

View File

@@ -1,5 +1,6 @@
package cn.lihongjie.coal.controller;
import cn.lihongjie.coal.annotation.Anonymous;
import cn.lihongjie.coal.annotation.SysLog;
import cn.lihongjie.coal.common.Ctx;
import cn.lihongjie.coal.dto.CaptchaDto;
@@ -25,6 +26,7 @@ public class LoginController {
@PostMapping("/login")
@SysLog(msg = "登录")
@Anonymous
public UserDto login(@RequestBody LoginDto dto) {
this.service.login(dto);
@@ -33,6 +35,7 @@ public class LoginController {
}
@PostMapping("/genCaptcha")
@Anonymous
public CaptchaDto genCaptcha() {
return this.service.genCaptcha();
@@ -47,9 +50,10 @@ public class LoginController {
}
@PostMapping("/isValid")
@Anonymous
public Boolean isValid() {
return Ctx.getUserId() != null;
return Ctx.isLoggedIn();
}