Adrian Cruz
08/13/2021, 12:56 PM@RequestBody body: MyDataClass
to get a deserialized object of the payload. but my problem is that i need to pass in the body as a String to validate the signature properly. Is there a proper way to handle this? or do i just update to @RequestBody body: String
, then do validation, and finally do a manual ObjectMapper
to MyDataClass
?Thomas
08/13/2021, 1:01 PMthanksforallthefish
08/13/2021, 1:22 PMimport javax.validation.Valid
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
class Controller {
@PostMapping //or get, or whatever method your webhook uses
fun webhook(@Valid @RequestBody body: MyDataClass)
}
class MyDataClass(
@get:ValidSignature
val signature: String
)
@Constraint(validatedBy = [ValidSignatureValidator::class])
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class ValidSignature(
val message: String = "Some error message",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<*>> = []
)
class ValidSignatureValidator : ConstraintValidator<ValidSignature, String> {
override fun isValid(value: String, context: ConstraintValidatorContext): Boolean =
...
this uses javax validation which I really really like since it gives you all violations at once (should have more) and automatically pinpoints the exact cause of the error.
javax validation is a specification, so you need an implementation as well. usually I go with hibernate validator, but there are also kotlin ones which might be more idiomatic (but I never tried them). for instance in gradle
implementation "org.hibernate.validator:hibernate-validator"
thanksforallthefish
08/13/2021, 1:24 PMthanksforallthefish
08/13/2021, 1:25 PMAdrian Cruz
08/13/2021, 1:28 PMAdrian Cruz
08/13/2021, 1:30 PM@RequestHeader(value = "X-XYZCorp-Signature") signature: String,
Adrian Cruz
08/13/2021, 1:31 PMthanksforallthefish
08/13/2021, 1:34 PM@ValidSignature @RequestHeader(value = "X-XYZCorp-Signature") signature: String,
should work in that casethanksforallthefish
08/13/2021, 1:35 PM@Valid
and/or
@Validated
class Controller
I am never sure thereAdrian Cruz
08/13/2021, 1:35 PMkqr
08/13/2021, 1:59 PMkqr
08/13/2021, 1:59 PMkqr
08/13/2021, 2:00 PMkqr
08/13/2021, 2:00 PMAdrian Cruz
08/13/2021, 2:03 PMAdrian Cruz
08/13/2021, 2:04 PMkqr
08/13/2021, 2:06 PMkqr
08/13/2021, 2:06 PMkqr
08/13/2021, 2:06 PMkqr
08/13/2021, 2:07 PMashmelev
08/13/2021, 2:07 PM@RequestBody
Object: ``
@JsonInclude(JsonInclude.Include.ALWAYS)
@JsonPropertyOrder("name", "type", "value")
Then you can simply convert the object to a JSON string, validate and dispose the String. This method also allows to you leave the @Validated
annotation intact so that Spring can take care of that for you as wellkqr
08/13/2021, 2:08 PMkqr
08/13/2021, 2:09 PMthanksforallthefish
08/13/2021, 2:18 PMkqr
08/13/2021, 2:22 PMAdrian Cruz
08/13/2021, 2:34 PMAdrian Cruz
08/13/2021, 2:34 PMthanksforallthefish
08/13/2021, 2:38 PMkqr
08/13/2021, 2:40 PM