Reputation: 10898
I have a REST API written in Spring with Spring Security and Spring Boot with the Web Started pack. Few of my methods inspect a JWT token:
@RequestMapping(value = "/list",
method = GET,
produces = APPLICATION_JSON_VALUE)
public HttpEntity<List<Item>> list(@RequestHeader(name = TOKEN_HEADER) String token) {
// validate token
// do something
}
Is it possible to move the token inspection to a method that would be invoked through the @PreAuthorize
annotation? Something like:
@RequestMapping(value = "/list",
method = GET,
produces = APPLICATION_JSON_VALUE)
@PreAuthorize("myMethod(headers)")
public HttpEntity<List<Item>> list(@RequestHeader(name = TOKEN_HEADER) String token) {
// do something
}
void myMethod(HttpHeaders headers) {
// validate token
}
The token contains some information about the resources that can be accessed by specific users. If the token doesn't contain the resource that the user requests or the data in underlying data layer indicate the user doesn't have access to it, I am returning HTTP 403.
Upvotes: 3
Views: 3423
Reputation: 77
You are trying to delegate authentication and authorization to the controller, and is not a good idea.
The way to deal with tokens on headers is to implement a filter that encapsulates the authentication and authorization by token and put in session the user and roles of the user logged.
Then the pre-authorization annotation checks context as you want.
You can see https://jwt.io/ to understand token flow.
Upvotes: 1