Using a filter to intercept a request
Such authentication can be achieved using ContainerRequestFilter
, intercepting requests to your resource methods.
The filter will be used to extract the API key from the request and validate it. If the API key is invalid, the request will be rejected. Otherwise, the request will go to resource methods.
Take a look at the following code snippet. ContainerRequestContext
API can be used to retrieve information from an HTTP request:
@Provider @Priority(Priorities.AUTHENTICATION) public class AuthenticationFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException {
Also see this answer. I wrote some time ago about authentication with tokens in JAX-RS. There you will find many details that may be useful to solve the situation described in your question.
User identification
During the authentication process, you should be able to identify the user making the request. To extend this information to your resource classes / methods, you could:
- Cancel the
SecurityContext
and enter it into your resource classes / methods. - Use the CDI
Event
and the producer method to create an object that contains a user ID that can be entered into your resource classes / methods.
See the answer I mentioned above for more details on these approaches.
Associating a filter with some resource classes / methods
By default, filters are global (this means that they are executed for all resource methods of your application). To associate a filter with a subset of methods or resource classes, you can use name binding annotations .
source share