【发布时间】:2017-09-23 18:21:48
【问题描述】:
如何使用 Spring Boot 在 html 元标记中获取 csrf 令牌?
我已经在 SPRING 中使用 xml 配置完成了 CSRF 令牌
目前我的项目在 SPRING BOOT 中。我尝试了很多,但没有运气。
我有一个 html 代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Boot project</title>
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="LoginPanel">
<form role="form" action="LoginAuth">
<input value="sample" type="text" name="Username" class="form-control" data-parsley-type="alphanum" placeholder="Username" required/>
<button type="submit" class="btn-block Signin btn btn-labeled1 btn-warning">
Sign in
</button>
</form>
</div>
<script>
$(document).ready(function()
{
var Form = $(".LoginPanel").find("form");
$(".LoginPanel").find("button.Signin").click(function(Event)
{
Event.preventDefault();
$.ajax(
{
type: "POST",
url: "LoginAuth",
data: Form.serialize(),
beforeSend: function (xhr,settings)
{
var CSRFToken = $("meta[name='_csrf']").attr("content");console.log(CSRFToken);
var CSRFHeader = $("meta[name='_csrf_header']").attr("content");console.log(CSRFHeader);
xhr.setRequestHeader(CSRFHeader, CSRFToken);
},
success: function(ResponseData, textStatus, jqXHR)
{
console.log(ResponseData);alert("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("Error");
}
});
});
});
</script>
</body>
</html>
我的安全配置是
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf();
}
}
application.properties
security.basic.enabled=false
security.enable-csrf=true
运行项目后,我仍然得到空令牌和标题名称
我希望这样的页面来源
<meta name="_csrf" content="7d789af1-996f-4241-ab70-2421da47bb09"/>
<meta name="_csrf_header" content="X-XSRF-TOKEN"/>
有可能吗?
谢谢
【问题讨论】:
-
先检查你的http响应,如果有csrf令牌存在
标签: java spring spring-boot spring-security csrf