使用带有csrf过滤器的jersey 1.1x创建Web服务

时间:2014-03-22 14:05:17

标签: java rest jersey

我需要使用jersey-server 1.17开发一个java REST webapp,我的资源需要避免csrf(跨站点请求伪造)攻击,我知道在jersey中存在一个可以做到这一点的类,这个类是csrfProtectionFilter所以我需要用这个过滤器检查每个请求,但我无法理解在何处以及如何插入此声明,我知道我必须将它放在web.xml中,但我还看不到任何好的结果,我试图修改一个球衣示例使用此web.xml

<servlet>
    <servlet-name>com.sun.jersey.samples.servlet.resources.MyApplication</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.sun.jersey.samples.servlet.resources.MyApplication</param-value>
    </init-param>  
    <init-param>
        <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
        <param-value>com.sun.jersey.api.container.filter.CsrfProtectionFilter</param-value>
    </init-param>      
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>com.sun.jersey.samples.servlet.resources.MyApplication</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

我忘记了什么吗?感谢。

2 个答案:

答案 0 :(得分:1)

我发现(几个月前!),这就是答案:

<servlet>
        <description></description>
        <display-name>Jersey REST Service</display-name>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
            <param-value>com.sun.jersey.api.container.filter.CsrfProtectionFilter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

答案 1 :(得分:0)

您需要将其添加到您的应用程序类中,如下所示:

@Application("/")

public class MyApplication extends ResourceConfig {

    public MyApplication() {
        super(YourResourceOrResources.class, CsrfProtectionFilter.class);
    }
}