User authentication on a Jersey REST service

Stefan picture Stefan · May 25, 2010 · Viewed 61.5k times · Source

I am developing a REST application, which is using the Jersey framework. I would like to know how I can control user authentication. I have searched many 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 with a GlassFish server and an 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.

Answer

Magnus Eklund picture Magnus Eklund · May 25, 2010

I'm sucessfully using spring security for securing my Jersey-based API. It has pluggable authentication schemes allowing you to switch from Basic Auth to something else later. I'm not using Spring in general, just the security stuff.

Here is the relevant part from my web.xml

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/security-applicationContext.xml,
        /WEB-INF/applicationContext.xml
    </param-value>
</context-param>

<!-- Enables Spring Security -->

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>springSecurityFilterChain</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>

</filter-mapping>

You can leave applicationContext.xml empty (<beans></beans>). An example of the security-applicationContext.xml can be found here