1

我的弹簧安全配置如下所示:

<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 的标头如下:

<headers>
    <header name="Content-Security-Policy" value="default-src 'self'"/>
</headers>

现在,我只想将此标头应用于我现在有 security="none" 的前两个 http 模式,而不是我在下一个 http 块中添加的其余 URL。我只是找不到办法。可能吗?有人可以建议吗?

我不需要为前两种模式定义 entry-point-ref。但是,删除 security="none" 会迫使我为它定义一个。请注意,我想要的只是能够为那些选定的模式启用 CSP,仅此而已。请帮忙!

更新:

4

1 回答 1

2

usingsecurity="none"意味着安全性不适用于 URL,因此将具有 Spring Security 的 Content Security Policy 添加到映射到的 URL 的声明security="none"是矛盾的。

我猜您想允许任何用户访问这些 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,则需要显式列出所有要启用的标头(添加任何显式标头意味着仅应用这些标头)。例如:

    <headers>
        <cache-control />
        <content-type-options />
        <hsts />
        <frame-options />
        <xss-protection />

        <header ref="headerWriter"/>
    </headers>

您可以在迁移指南中找到有关差异的更多详细信息。

于 2015-12-17T22:21:30.930 回答