使用Wildfly Swarm的REST API CORSFilter
问题描述:
我已经开发了使用Wildfly Swarm的REST API,并且我想介绍CORS过滤器,并且我的要求是所有头/值都应该可以在外部资源中配置。使用Wildfly Swarm的REST API CORSFilter
我已经实现了CORSFilter,但具有硬编码的标题值,但现在我希望它可以配置为Production环境。
任何人都可以引导我吗?
答
我使用属性文件确切地解决了这个问题。
我有以下文件
- 的src /主/资源/ cors.properties
- 的src /主/资源/ cors.stage.properties
- 的src /主/资源/ cors.prod。属性
比我使用maven-antrun-plugin根据选定的maven配置文件使用正确的属性文件。
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete file="${project.build.outputDirectory}/cors.properties"/>
<copy file="src/main/resources/cors.prod.properties"
tofile="${project.build.outputDirectory}/cors.properties"/>
<delete file="${project.build.outputDirectory}/cors.stage.properties"/>
<delete file="${project.build.outputDirectory}/cors.prod.properties"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
请检查https://maven.apache.org/guides/mini/guide-building-for-different-environments.html了解完整的maven配置。
然后你可以从你的资源加载的属性,遍历它们,并添加页眉
Properties properties = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream("cors.properties");
properties.load(in);
in.close();
for (String name : properties.stringPropertyNames()) {
addHeader(name, properties.getProperty(name));
}
答
您可以使用项目 - <轮廓> .yml更改数值取决于个人资料(如违约,生产,...)。
https://reference.wildfly-swarm.io/v/2017.3.2/configuration.html#_using_yaml
WRT CORSFilter,你可以与@ConfigurationValue的YML注入值。
import org.wildfly.swarm.spi.runtime.annotations.ConfigurationValue;
@ApplicationScoped
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Inject @ConfigurationValue("access-control-max-age")
private int accessControlMaxAge;
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext throws IOException {
responseContext.getHeaders().add(
"Access-Control-Max-Age",
accessControlMaxAge // Injected value
);
// other headers ...
}
}
或者,您可以使用Undertow过滤器而不是使用yml代替CORSFilter。
swarm:
undertow:
filter-configuration:
response-headers:
access-control-max-age:
header-name: Access-Control-Max-Age
header-value: -1
# other headers configuration
servers:
default-server:
hosts:
default-host:
filter-refs:
access-control-max-age:
priority: 1
# other filter refs
我创建了一个例子有两种方式。
https://github.com/emag-wildfly-swarm-sandbox/wildfly-swarm-cors-filter-demo
我不认为我们现在有一个办法设置CORS标头在我们的项目defaults.yml配置。 你能提出一个问题吗? https://issues.jboss.org/browse/SWARM – Ken