How do I add a custom HTTP request header to a form or Thymeleaf link?

We use JWT authentication in the Spring boot application. To protect against CSRF attacks, we want to send the token back to the server in a custom HTTP header instead of a cookie.

Is there a way to force Thymeleaf to use XMLHttpRequest for generated links? We do not want to scroll through the templates, replacing all h: href anchors with onclick javascript handlers.

+4
source share
1 answer

short answer: no!

: , . Thymeleaf - HTML/XML. XMLHttpRequest, AJAX (*), javascript.

, javascript. javascript, . javascript . Thymeleaf .

* : , , ;)


, [. ]:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.w3.org/1999/xhtml"
      layout:decorator="Layout">
    <head>
        <title>Example</title>

        <meta name="_jwt" th:content="${yourToken}"/>
    </head>
    ...

ajax .

, jQuery, ajax jQuery :

$(function(){
    var _token = $('meta[name="_jwt"]').attr('content');

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        jqXHR.setRequestHeader("your_jwt_token_header_name", _token);
    });
});
+2

Source: https://habr.com/ru/post/1659622/


All Articles