Jersey REST服务上的用户身份validation

我正在开发一个使用Jersey框架的REST应用程序。 我想知道我可以如何控制用户身份validation。 我search了很多地方,最近发现的文章是这样的: http : //weblogs.java.net/blog/2008/03/07/authentication-jersey 。

但是,本文只能与GlassFish服务器和附加数据库一起使用。 无论如何,我可以在Jersey中实现一个接口,并在到达请求的REST资源之前将其用作filter?

我现在想要使用基本身份validation,但它应该足够灵活,以便以后可以更改。

我成功地使用spring安全来保护我的基于Jersey的API。 它具有可插拔的身份validationscheme,可以让您在稍后从基本身份validation切换到其他方法。 一般来说,我并没有使用Spring,只是安全的东西。

这是我的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> 

您可以将applicationContext.xml留空(<beans> </ beans>)。 security-applicationContext.xml的例子可以在这里find

我正在做类似的事情。 在我的实现中,我们有Apache httpd前端来处理HTTP基本身份validation,它只是简单地转发所有请求包含用户和angular色的头信息。

从这一点上,我正在使用Servletfilterparsing这些部分,使用CodeRanch上发布的post来包装HttpServletRequest 。 这使我可以在每个我想要过滤的资源上使用像@RolesAllowed这样的javax.annotation.security注解。 但是,为了使所有这些工作都能正常工作,我必须在web.xml中将下列内容添加到我的servlet中:

 <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> 

您可能会发现Eric Warriner在最近的一篇关于感兴趣的post( Jersey,Tomcat和Security Annotations)上的回答

看看这里,我正在尝试,但它看起来很有希望:

http://anismiles.wordpress.com/2012/03/02/securing-versioning-and-auditing-rest-jax-rs-jersey-apis/

这个例子比试图实现JASPI / JASPIC要简单得多,并且为单个方法(@RolesAllowed,@ PermitAll,@ DenyAll等等)提供了更好的粒度。

(我知道这是一个旧线程,但只是添加可能有用的信息)

当然,你可以使用传统的servletfilter。

将filter添加到您的web.xml,检查您使用的任何validation头(基本或摘要),根据这些值执行validation逻辑,并将结果存储在会话属性中。 在您的Jersey资源(可能是ctor)中,从会话属性中提取auth结果并根据这是否是您需要的结果继续处理。

你的Jersey资源库可能看起来像这样:

 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 } 

你可以通过两种方式来完成,你可以编写一个简单的servletfilter,或者你必须实现一个ResourceFilterFactory并在ContainerRequestFilter中处理auth。 详细代码位于链接http://neopatel.blogspot.com/2011/11/jesey-writing-authentication-filter.html 。 我个人喜欢servletfilter方法,因为它提供了完整的生命周期控制。 但是,如果你需要更多的特定的东西,比如访问QueryParams或PathParams,那么ResourceFilterFactory就是要走的路。