Reputation: 311
How can i put CSRF token in form using JTwig?
I tried this extension but it doesn't work (showing error about {% csrf %} has no endblock). Also i tried putting HttpServletRequest object in model and then get token using this snippet, but it had no effect at all.
Is there some generic way to implement csrf-token even without template engine?
Upvotes: 1
Views: 489
Reputation: 364
The following code worked for me:
I created a class called ControllerSetup (or you can name it anything you want) and I placed it inside the same folder as my Application class (the one with the public static void main()
method). The code is as follows:
package some.pkg.of.myapp;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class ControllerSetup {
@ModelAttribute
public void initModel(HttpServletRequest request, Model model) {
model.addAttribute("_csrf", request.getAttribute("_csrf"));
}
}
Now, any model in any of my controllers will automatically have an attribute called _csrf. I would use it in my JTwig forms as follows:
<form method="post" action="/some/action/url">
<!-- My fields and buttons here -->
<input type="hidden"
name="{{ _csrf.parameterName }}" value="{{ _csrf.token }}" />
</form>
Upvotes: 3