I have a RestController defined as follows:
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.PostMapping
import javax.validation.Valid
@RestController
class CaseController(
private val caseService: CaseService,
private val remoteFileService: RemoteFileService,
private val clientService: ClientService
) {
@PostMapping("/api/v1/cases", consumes = [MediaType.APPLICATION_JSON_VALUE])
@NeedsAuth
fun createCase(
@RequestBody @Valid caseCreationRequest: CaseCreationRequest,
@RequestHeader("Api-Key", required = false) apiKey: String,
): ResponseEntity<Case> { }
I have defined NeedsAuth
as an annotation.
The problem is that the @Valid
annotation is being called before @NeedsAuth
.
If I send invalid request body with invalid authentication, I receive "Validation Error" as response.
If I send valid request body with invalid authentication, I receive "Authentication Error".
If I remove @Valid
annotation from code and then send invalid request body with invalid authentication, I receive "Authentication Error".
What I want this to do?
I want it to call @NeedsAuth before @Valid.
Any help is greatly appreciated.
Thanks
Update:
Code related to handling of @NeedsAuth
:
//NeedsAuth.kt
package com.jimdo.debtcollectionservice.adapters.apis.http.auth
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class NeedsAuth
//AuthAspect.kt
package com.jimdo.debtcollectionservice.adapters.apis.http.auth
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
@Component
@Aspect
class AuthAspect {
@Autowired
lateinit var authTokenHandler: AuthTokenHandler
@Before("execution(* *.*(..)) && @annotation(NeedsAuth)")
fun validateToken(joinPoint: JoinPoint) {
val request = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes).request
authTokenHandler.authenticateToken(request.getHeader("Api-Key"))
}
}