0

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.

For example, I have 3 APIs. 1. RestAPI/test1 2. RestAPI/test2 3. RestAPI/test3

so before doing the query, I want to check that user is authenticated or not.

Can i use ConstraintValidator?

How can i achieve this?

I am not using spring boot...

Thanks!

Jayesh Dhandha
  • 1,983
  • 28
  • 50

1 Answers1

0

There are following ways to do it:

1) Spring security @PreAuthorize("isAuthenticated()") or @Secured("ROLE_ADMIN")

See the thread for more info

2) You can create custom annotation, add aspect with SecurityContextHolder check in it :

@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();
    }
}

For second approach you probably need to add proxy-target-class="true" <aop:aspectj-autoproxy proxy-target-class="true"/>

i.bondarenko
  • 3,442
  • 3
  • 11
  • 21