Today I implemented a javax.ws.rs.client.ClientRequestFilter for a form based authentication. The FormAuthenticator class can be used in combination with a javax.ws.rs.client.Client to interact, for example, with a rest api secured by a login form. Such a login form in Java EE typically uses the request URI ‘/j_security_check‘ with the form input fields ‘j_username’ and ‘j_password‘. As a result of a successful login the browser stores a cookie named “JSESSIONID” which need to be send with every request.
The request filter can be added to a javax.ws.rs.Client like this:
.... // create a javax.ws.rs.client client = ClientBuilder.newClient(); // create new formAuthenticator FormAuthenticator formAuthFilter = new FormAuthenticator(rest_api_url, userid, password); // register the filter... client.register(formAuthFilter); // now you can GET, POST, .... ....
You cam find the source code of this filter class on GitHub.
If you have any ideas for improvements your comments are welcome!
Hello Ralph,
I was wondering do you login for every invocation? how about log-off? do you handle that?
Another point is that, I notice your ClientRequestFilter is not annotated with @Provider. Yet javadoc states:
“An extension interface implemented by client request filters. Filters implementing this interface MUST be annotated with @Provider. This type of filters is supported only as part of the Client API.”
I am also working on something similar, but I think I do need to make sure to log-off every after invocation. Any advice is much appreciated.
Thanks for this hint. Yes I think the @Provider annotation should be added.
For your question about the login/logout issue: If you have the JSESSON cookie you do not need to re-login. In my own use cases the client is used by stateless microservices so I do not store any session information.
For a logout you application should provide a suitable ressource (…/?logout), because in form-based authentication there is no standard for logout. This is at least my understanding for form-based authentication. If you have information here lets discuss this.