I've written a simple REST server using JAX-RS, Jersey and Grizzly. This is how I start the server:
URI baseUri = UriBuilder.fromUri("http://localhost/api")
.port(8081)
.build();
ResourceConfig rc = new PackagesResourceConfig("se.aioobe.resources");
HttpServer httpServer = GrizzlyServerFactory.createHttpServer(baseUri, rc);
Now I need to protect the resources using Basic HTTP authentication, and I can't figure out how to do this.
I can switch from Grizzly to for instance Jetty if it is simpler to get it to work, but I really value the simple configuration / start up that Grizzly provides.
I've read a lot of tutorials. They all mention the web.xml but in my current configuration I don't have one. (Do I need to add one for HTTP authentication?) I've found the following questions, neither of them is of any help :-(
(No SSL required at this point. The authentication is at this point just to prevent the public from peeking at our beta.)
TL;DR: How do I add basic HTTP authentication to a Jersey / Grizzly webapp?
You may want to check HTTPS Client Server Grizzly sample distributed with Jersey which exactly does that. Here is a gist from that sample on configuring security filters on the Grizzly server.
You are registering a SecurityFilter which takes care of your HTTP basic auth. Enabling logging filter on the server should show basic auth header in the request. Here is an example:
I managed to get it working after a couple of hours, based on this blog post.
My solution involves:
I created this
ContainerRequestFilter
:And I then changed the startup code to include the filter:
@aioobe be aware that although this will kind-of work you need better error checking when you're working with the header. For example:
This assumes that the authentication header is Basic, whereas it might not be. You should check that the authorization header starts with 'Basic' and if not throw unauthorized. Same thing for ensuring that the rest of the information is actually base64-encoded.