使用 Spring Security 3.2.0.RELEASE,如何在没有标签库的纯 HTML 页面中获取 CSRF 令牌 [英] With Spring Security 3.2.0.RELEASE, how can I get the CSRF token in a page that is purely HTML with no tag libs

查看:16
本文介绍了使用 Spring Security 3.2.0.RELEASE,如何在没有标签库的纯 HTML 页面中获取 CSRF 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我从具有独立 java 配置依赖项的 Spring Security 3.1.4 升级到包含 java 配置的新 3.2.0 版本.CSRF 默认开启,我知道我可以在我的覆盖配置方法中使用http.csrf().disable()"禁用它.但是假设我不想禁用它,但我需要在我的登录页面上使用 CSRF 令牌,其中没有使用 JSP 标记库或 Spring 标记库.

Today I upgraded from Spring Security 3.1.4 with the separate java config dependency, to the new 3.2.0 release which includes java config. CSRF is on by default and I know I can disable it in my overridden configure method with "http.csrf().disable()". But suppose I don't want to disable it, but I need the CSRF token on my login page where no JSP tag libs or Spring tag libs are being used.

我的登录页面纯粹是 HTML,我在使用 Yeoman 生成的 Backbone 应用程序中使用了它.我将如何将包含在 HttpSession 中的 CSRF 令牌包含在表单或标题中,以便我不会收到未找到预期的 CSRF 令牌.您的会话是否已过期?"例外?

My login page is purely HTML that I use in a Backbone app that I've generated using Yeoman. How would I go about including the CSRF token that's contained in the HttpSession in either the form or as a header so that I don't get the "Expected CSRF token not found. Has your session expired?" exception?

推荐答案

您可以使用 参考.要将 CSRF 添加到 HTML 页面,您需要使用 JavaScript 获取需要包含在请求中的令牌.

You can obtain the CSRF using the request attribute named _csrf as outlined in the reference. To add the CSRF to an HTML page, you will need to use JavaScript to obtain the token that needs to be included in the requests.

将令牌作为标头返回比在正文中作为 JSON 返回更安全,因为正文中的 JSON 可以通过外部域获取.例如,您的 JavaScript 可以请求由以下处理的 URL:

It is safer to return the token as a header than in the body as JSON since JSON in the body could be obtained by external domains. For example your JavaScript could request a URL processed by the following:

CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
// Spring Security will allow the Token to be included in this header name
response.setHeader("X-CSRF-HEADER", token.getHeaderName());
// Spring Security will allow the token to be included in this parameter name
response.setHeader("X-CSRF-PARAM", token.getParameterName());
// this is the value of the token to be included as either a header or an HTTP parameter
response.setHeader("X-CSRF-TOKEN", token.getToken());

然后,您的 JavaScript 将从响应头中获取头名称或参数名称和令牌,并将其添加到登录请求中.

Your JavaScript would then obtain the header name or the parameter name and the token from the response header and add it to the login request.

这篇关于使用 Spring Security 3.2.0.RELEASE,如何在没有标签库的纯 HTML 页面中获取 CSRF 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆