How to use spring boot to get a csrf token in an html meta tag… here is a solution to the problem.
How to use spring boot to get a csrf token in an html meta tag
How do I get a CSRF token in an HTML meta tag using Spring Boot?
I already done the CSRF token in SPRING by using xml configuration
CURRENTLY MY PROJECT IS IN SPRING BOOT. I tried a lot but had no luck.
I have an html code
<! 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>
My security configuration is
@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
After running the project, I still get empty token and header names
I want the page source code to look like this
<meta name="_csrf" content="7d789af1-996f-4241-ab70-2421da47bb09"/>
<meta name="_csrf_header" content="X-XSRF-TOKEN"/>
Is this possible?
Thanks
Solution
You didn’t show that the content
property was dynamic in any way, so it wasn’t handled. You didn’t specify what templating engine you’re using, but this one looks like Thymeleaf, so your tag should look like this:
<meta name="_csrf" data-th-content="${_csrf.token}" />