I have a Spring 3.2 application and I've created a REST API that uses a token-based security. Every REST JSON payload contains a "token" field that is used to perform security validation.
The controller methods are like this:
@RequestMapping(value = "/something", method = RequestMethod.POST)
public
@ResponseBody
Map something(@RequestBody SomethingParams params) {
}
where SomethingParams has a token
field, and is automatically filled in by Spring from the JSON body of the request.
Is there a way to automatically have a validator invoked on all the controller methods to check that parameters such as SomethingParams have a valid token?
Previously I used an Interceptor, and the token was included in the query string, but now, since it's in the body of the request, I would have to parse the JSON in the interceptor in order to check it. Since Spring already parses the JSON to bind the parameters, I'm curious if there's a smarter way. Ideally just with some global or controller-level settings (not per method).
You can make base class with token field annotated with
JSR-303 @NotNull
and extend from it.And then just mark parameter with
@Valid
:Spring will automatically validate parameter with JSR-303 implementation available at runtime.
I usually use hibernate-validator as implementation provider:
You can also implement your own
Aspect
, which will intercept all controller methods and validate params. This will give you opportunity to get rid of@Valid
annotation. But unfortunately I don't have time for full example.You can use a spring
Validator
for such cases.Then you register it in your
Controller
by adding the following methodFinally all you have to add is the
@Valid
annotation on yourSomethingParams
object and it will be validated.