我正在使用Spring Rest API,并且我想在进入rest api查询之前应用自定义验证(更具体地说,我想检查用户是否经过身份验证,因此我还需要HttpServletRequest
对象)。
例如,我有 3 个 API。 1.RestAPI/测试1 2.RestAPI/测试2 3.RestAPI/test3
所以在执行查询之前,我想检查用户是否经过身份验证。
我可以使用 ConstraintValidator
?
我怎样才能实现这个目标?
我没有使用 Spring Boot...
谢谢!
最佳答案
有以下几种方法:
1)Spring安全@PreAuthorize("isAuthenticated()")
或@Secured("ROLE_ADMIN")
请参阅thread了解更多信息
2) 您可以创建自定义注释,添加方面 SecurityContextHolder
检查一下:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Authenticated {
}
import org.aspectj.lang.annotation.Aspect;
@Aspect
@Component
public class AuthenticatedAspect {
@Around("@annotation(Authenticated)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
throw your exeption
}
return joinPoint.proceed();
}
}
对于第二种方法,您可能需要添加 proxy-target-class="true"
<aop:aspectj-autoproxy proxy-target-class="true"/>
关于java - 对 Spring Rest API 的所有查询进行自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558450/