首页 > 解决方案 > spring rest API 的所有查询的自定义验证

问题描述

我正在使用 Spring Rest API,并且我想HttpServletRequest在进入 rest api 查询之前应用自定义验证(更具体地说,我想检查用户是否经过身份验证,因为我也需要对象)。

例如,我有 3 个 API。1.RestAPI/test1 2.RestAPI/test2 3.RestAPI/test3

所以在进行查询之前,我想检查用户是否经过身份验证。

我可以用ConstraintValidator吗?

我怎样才能做到这一点?

我没有使用弹簧靴......

谢谢!

标签: javaspringrestapispring-security

解决方案


有以下方法可以做到:

1)弹簧安全@PreAuthorize("isAuthenticated()")@Secured("ROLE_ADMIN")

有关更多信息,请参阅线程

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"/>


推荐阅读