我的 spring 安全配置如下所示:
<http pattern="/*/yyy/**" security="none" />
<http pattern="/*/zzz/**" security="none"/>
<http create-session="stateless" use-expressions="true">
<csrf disabled="true" />
<intercept-url method="GET" pattern="/*/api/products" access="xxxx" />
<http-basic entry-point-ref="customBasicAuthenticationEntryPoint" />
</http>
现在,对于上面带有 security="none"的 http 模式,我想为此启用内容安全策略 (CSP)。只要我保持 security="none",我认为我就无法对其应用 CSP。
在 Spring Security 中启用 CSP 的 header 如下:
<headers>
<header name="Content-Security-Policy" value="default-src 'self'"/>
</headers>
现在,我只想将此 header 应用于我现在有 security="none"的前两个 http 模式,而不应用于我在下一个 http block 中添加的其余 URL。我只是找不到办法做到这一点。是否可以?有人可以建议一下吗?
我不需要为前两个模式定义入口点引用。但是,删除 security="none"会迫使我为其定义一个。请注意,我想要的只是能够为这些选定的模式启用 CSP,仅此而已。请帮忙!
更新:
最佳答案
使用security="none"
意味着安全性不会应用于URL,因此使用Spring Security向使用security="none"映射的URL添加内容安全策略的语句
是矛盾的。
我猜测您希望允许任何用户访问这些 URL。如果是这种情况,您可以轻松使用 permitAll
表达式。
然后,您可以使用DelegatingRequestMatcherHeaderWriter指定哪些URL设置了内容安全策略。 。例如,使用 Spring Security 4+ 您可以使用:
<http>
<intercept-url pattern="/*/yyy/**" access="permitAll" />
<intercept-url pattern="/*/zzz/**" access="permitAll"/>
<intercept-url method="GET" pattern="/*/api/products" access="xxxx" />
<headers>
<header ref="headerWriter"/>
</headers>
<csrf disabled="true" />
<http-basic entry-point-ref="customBasicAuthenticationEntryPoint" />
<!-- ... -->
</http>
<beans:bean id="headerWriter"
class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.util.matcher.OrRequestMatcher">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
c:pattern="/*/yyy/**"/>
<beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
c:pattern="/*/zzz/**"/>
</beans:constructor-arg>
</beans:bean>
</beans:constructor-arg>
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.web.header.writers.StaticHeadersWriter"
c:headerName="Content-Security-Policy"
c:headerValues="default-src 'self'"
/>
</beans:constructor-arg>
</beans:bean>
请注意,如果您使用的是 Spring Security 3,那么您将需要显式列出您想要启用的所有 header (添加任何显式 header 意味着仅应用这些 header )。例如:
<headers>
<cache-control />
<content-type-options />
<hsts />
<frame-options />
<xss-protection />
<header ref="headerWriter"/>
</headers>
您可以在the migration guide中找到有关差异的更多详细信息。 .
关于java - 如何在 Spring Security 中启用选择性 http 模式的内容安全策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34344840/