【问题标题】:Configuration of Apache CXF CrossOriginResourceSharingFilter with Spring使用 Spring 配置 Apache CXF CrossOriginResourceSharingFilter
【发布时间】:2015-12-13 10:02:29
【问题描述】:

如何在不更改源代码(带注释的类或 beans.xml)的情况下配置 Apache CXF CrossOriginResourceSharingFilter

JAX-RS: CORS example 中配置是硬编码的:

这里是测试代码,展示了如何在资源和单个方法级别应用 CrossOriginResourceSharing 注释。

[...]

@GET
@CrossOriginResourceSharing(
     allowOrigins = { "http://area51.mil:31415" }, 
     allowCredentials = true, 
     exposeHeaders = { "X-custom-3", "X-custom-4" }
)
@Produces("text/plain")
@Path("/annotatedGet/{echo}")
public String annotatedGet(@PathParam("echo") String echo) {
    return echo;
}

我使用 beans.xml 来配置 allowOrigins 属性:

<bean id="cors-filter" class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter">
    <property name="allowOrigins">
        <list>
            <value>myserver1</value>
            <value>myserver2</value>
        </list>
    </property>
</bean>

我以为我可以从 JNDI 获取该属性,但不允许添加 List(请参阅 Servlet Specification 2.5)。我需要一种方法来为 CORS * 配置一个空的 List

<bean id="cors-filter"
    class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter">
    <property name="allowOrigins"><
        <jee:jndi-lookup jndi-name="CORS/origins"/>
    </property>
</bean>

在可重用 WAR 中配置 CrossOriginResourceSharingFilter 的预期/首选方式是什么?

【问题讨论】:

    标签: java spring cors jax-rs cxf


    【解决方案1】:

    如果您使用一些环境变量来设置一个以逗号分隔的来源列表,如下所示:

    <bean id="cors-filter"
        class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter">
            <property name="allowOrigins" value="#{systemProperties['origins'] != null ? systemProperties['origins'].split(',') : null}"> 
        </property>
    </bean>
    
    • 这是经过测试的代码

    并将-Dorigins=or1,or2,... 传递给JVM(或不传递以获取空值)

    如果您需要在配置中传递一个空列表,您可以像这样编辑代码(将属性值中的null 替换为{}):

    <bean id="cors-filter"
        class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter">
             <property name="prop" value="#{systemProperties['test'] != null ? systemProperties['test'].split(',') : {}}">
             </property>
    </bean>
    

    这样,如果您将 -Dorigins 添加到 Java VM 选项,将使用一个空列表。

    基于Spring EL Documentation,您可以使用所有对象方法:

    作为方法调用的示例,我们在字符串文字上调用“concat”方法。 Expression exp = parser.parseExpression("'Hello World'.concat('!')");

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 2019-04-26
      • 2012-09-07
      • 1970-01-01
      相关资源
      最近更新 更多