gpt4 book ai didi

java - 如何使用 spring boot 在 html 元标记中获取 csrf token

转载 作者:行者123 更新时间:2023-11-29 09:27:55 27 4
gpt4 key购买 nike

如何使用 spring boot 在 html 元标记中获取 csrf token ?

I already done the CSRF token in SPRING by using xml configuration

目前我的项目在 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();
}
}

应用程序属性

security.basic.enabled=false
security.enable-csrf=true

运行项目后,我仍然得到空 token 和 header 名称

我希望页面源代码是这样的

<meta name="_csrf" content="7d789af1-996f-4241-ab70-2421da47bb09"/>
<meta name="_csrf_header" content="X-XSRF-TOKEN"/>

这可能吗?

谢谢

最佳答案

您并没有表明 content 属性在任何方面都是动态的,因此它没有得到处理。您没有指定您使用的是什么模板引擎,但是这个看起来像 Thymeleaf,所以您的标签应该是这样的:

<meta name="_csrf" data-th-content="${_csrf.token}" />

关于java - 如何使用 spring boot 在 html 元标记中获取 csrf token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632647/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com