繁体   English   中英

如何在Spring Security中为选择性的HTTP模式启用内容安全策略

[英]How to enable content security policy to selective http patterns in spring security

我的春季安全配置看起来像:

<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。 我只是找不到办法。 可能吗? 有人可以建议吗?

我不需要为前两种模式定义入口点引用。 但是,删除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,则需要显式列出要启用的所有标头(添加任何显式标头意味着仅应用那些标头)。 例如:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM