簡體   English   中英

自定義驗證 spring rest API 的所有查詢

[英]Custom validation for all the query of spring rest API

I am using Spring Rest API, and i want to apply custom validation (To be more specific, i want to check user authenticated or not so for that i need HttpServletRequest object also) before going inside the rest api query.

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

所以在進行查詢之前,我想檢查用戶是否經過身份驗證。

我可以使用ConstraintValidator嗎?

我怎樣才能做到這一點?

我沒有使用 spring 引導...

謝謝!

有以下方法可以做到:

1) Spring 安全@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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM