Reputation: 822
How can i get csrf token in html meta tags 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 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 config 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 run the project, still i get the the null token & header name
I expected from the page source like this
<meta name="_csrf" content="7d789af1-996f-4241-ab70-2421da47bb09"/>
<meta name="_csrf_header" content="X-XSRF-TOKEN"/>
Is it possible?
Thanks
Upvotes: 3
Views: 4081
Reputation: 77177
You're not indicating that the content
attribute is dynamic in any way, so it's not getting processed. You didn't specify what template engine you're using, but this looks like Thymeleaf, so here's what your tag should look like:
<meta name="_csrf" data-th-content="${_csrf.token}" />
Upvotes: 3