views:

1131

answers:

3

I am currently developing a REST application, which is using the Jersey framework. I would like to know a way that I can control user authentication. I have search a lot of places, and the closest article I have found is this: http://weblogs.java.net/blog/2008/03/07/authentication-jersey.

However this article can only be used whith a GlassFish server and a attached database. Is there anyway that I can implement an interface in Jersey and use it as a filter before reaching the requested REST resource?

I want to use basic authentication right now, but it should be flexible enough such that I can change that at a later time.

Thanks in Advance Stefan.

A: 
+1  A: 

I'm working on something similar to this. In my implementation, we have Apache httpd front-ended to handle HTTP Basic authentication and it simply forwards all requests with some header information containing the user and roles.

From that, I'm working on parsing these pieces out using a servlet filter to wrap the HttpServletRequest using a post I found on CodeRanch. This allows me to use the javax.annotation.security annotations like @RolesAllowed on each resource I want to filter. To get all of these pieces working, however, I had to add the following to my servlet in the web.xml:

<servlet>
  <!-- some other settings and such 
  ... -->
  <init-param>
    <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory</param-value>
  </init-param>
  ...
</servlet>

You might find that Eric Warriner's answer on a recent post of interest: http://stackoverflow.com/questions/2291323/jersey-spring-tomcat-and-security-annotations

Nick Klauer
A: 

Sure, you can use a traditional servlet filter for this.

Add the filter to your web.xml, check for whatever authentication headers you're using (Basic or Digest), perform your authentication logic based on those values, and store the result in a session attribute. In your Jersey resource (ctor probably), extract the auth result from the session attribute and continue processing or not based on whether this is the result you require.

Your Jersey resource ctor would probably look like this:

protected AbstractResource(@Context ServletContext servletContext, @Context HttpServletRequest httpServletRequest) {...

HttpSession session = httpServletRequest.getSession(); // get whatever you put in the session in the auth filter here and compare }

ae6rt