使用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

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

问题描述

今天,我从具有单独的java config依赖项的Spring Security 3.1.4升级到了新的3.2.0版本,其中包括java config. CSRF默认情况下处于打开状态,我知道可以使用"http.csrf().disable()"在覆盖的configure方法中将其禁用.但是,假设我不想禁用它,但是我需要在登录页面上使用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?

推荐答案

您可以使用

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天全站免登陆