我们有一个 Java 类,它扩展了 Spring 的
WebSecurityConfigurerAdapter
并设置了所有安全标头等。只留下代码的相关部分,目前是这样的:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
...
http.headers()
...
.and()
.crossOriginResourcePolicy()
.policy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN)
.and()
...;
}
(使用 spring-framework.version 5.3.39;org.springframework.boot/spring-boot-starter-parent 2.7.18;和 JDK 版本 21)
如果有人现在尝试通过他们自己的网站访问我们网站上的图像,例如
test.html
文件。<html><body> <img src="https://myexamplewebsite.com/animals/uploaded_documents/dog.jpg"> </body></html>
。他们会看到损坏的图像并收到以下控制台错误(在 Google Chrome 中测试):
获取https://myexamplewebsite.com/animals/uploaded_documents/dog.jpgnet::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin 200(确定)
这符合预期。
但是,我想对来自特定路径的资源图像的上述标头进行例外处理(例如
/public_resources/**
)。https://myexamplewebsite.com/public_resources/logo.jpg
的错误。public_resources
URL 的所有其他标头,以及不在该 Cross-Origin-Resource-Policy
路径中的所有图像(和其他资源)的 same-origin
/public_resources/**
标头。
PS:我们的主机网站,我在我的问题中使用了
https://myexamplewebsite.com
,是基于客户和该公司内可选分支的通用网站(例如https://branchname.companyname.nl/
或https://companyname.nl/
),所以我无法硬编码它在我定义的标题中。
我尝试通过在
crossOriginResourcePolicy()
方法中的其他所有内容之后添加以下内容来覆盖 Spring 的标准 configure
实现:
http.antMatches("/public_resources/**")
.headers()
.addHeaderWriter(new StaticHeadersWriter("Cross-Origin-Resource-Policy", "none"))
但这不仅会覆盖该标题,还会由于某种原因覆盖几乎所有内容,以及其他页面上的内容。
我也尝试过与这个答案类似的方法,创建一个单独的类,
extends WebSecurityConfigurerAdapter
,并在其覆盖的配置方法中执行上面的代码片段,但这也不起作用。
不知道为什么我的问题遭到了很多反对,但由于我在同事的帮助下找到了解决方案,我将把这个问题留给其他想要完成同样事情的人。
虽然
.antMatcher(String)
缺乏“正则表达式”的任何反转功能,但还有一个实际的正则表达式匹配器方法可用:.regexMatcher(String)
。
所以我从原始代码中删除了它:
.and()
.crossOriginResourcePolicy()
.policy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN)
稍后添加:
// Set the following header(s) on each request as well, with the sole exception
// of requests that access the resources within the /public_resources/** folder:
http.regexMatcher("^(?!/public_resources/).*$")
.headers()
.crossOriginResourcePolicy()
.policy(CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy.SAME_ORIGIN);
现在,来自此
public_resources
域路径的图像将没有 Cross-Origin-Resource-Policy
标头,因此可以查看,但每个其他图像/资源都将具有此标头,并且无法从外部源中查看。