使用 Spring 安全保护 Web 应用程序免受 CSRF 攻击

Protecting web application from CSRF attack using Spring Security

我正在我的 Web 应用程序中实施 CSRF 保护。

我已经使用 org.springframework.security.web.csrf.CookieCsrfTokenRepository class 生成了 X-XSRF 令牌。此令牌在每个请求的响应中作为 cookie 发送。

UI 组件是部署在不同服务器上的单页应用程序,它读取此 cookie 并从 cookie 读取 X-XSRF 令牌,并在所有后续请求中将其设置为 header。

Spring 验证收到的 X-XSRF 令牌和 allow/deny 请求。这很好用。

但是他们的限制是这个 X-XSRF cookie 必须是 httpOnlyfalse 以便客户端 JavaScript 可以读取它。

我们无法读取 httpOnlytrue 的 cookie。

在 X-XSRF 令牌 cookie httpOnlytrue.

的 Web 应用程序中,是否有任何其他替代方法来保护 Web 应用程序 CSRF

使用 JavaScript 方法 (document.cookie) 我无法读取 httpOnly 属性设置为 true 的 cookie,请参阅:

我无法进行更改以生成所有 cookie,因为 httpOnly 在 Websphere 中是 false

或者我是否遗漏了客户端 JavaScript 可以读取 httpOnly 的 cookie 的内容 true

参见Spring Security Reference:

CookieCsrfTokenRepository

There can be cases where users will want to persist the CsrfToken in a cookie. By default the CookieCsrfTokenRepository will write to a cookie named XSRF-TOKEN and read it from a header named X-XSRF-TOKEN or the HTTP parameter _csrf. These defaults come from AngularJS

You can configure CookieCsrfTokenRepository in XML using the following:

<http>
    <!-- ... -->
    <csrf token-repository-ref="tokenRepository"/>
</http>
<b:bean id="tokenRepository"
    class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
    p:cookieHttpOnly="false"/>

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false to improve security.

You can configure CookieCsrfTokenRepository in Java Configuration using:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false (by using new CookieCsrfTokenRepository() instead) to improve security.