如何使用Spring Boot在HTML Meta标签中获得CSRF令牌



如何使用Spring Boot在HTML Meta标签中获得CSRF令牌?

我已经使用XML Configuration在春季完成了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

运行项目后,我仍然得到了零令牌&amp;标题名称

我从页面来源期望这样的

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

可能吗?

谢谢

您没有以任何方式表明content属性是动态的,因此它不会被处理。您没有指定您正在使用的模板引擎,但是This 看起来像胸腺,所以这是您的标签外观:

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

最新更新