Many of you who have worked on Spring Security might be aware of the fact that Spring Security protects applications from Cross Site Request Forgery using _csrf tokens in the request sent to the web server. You can find a detailed understanding in the Spring documentation page. The objective of this post is to explain how to send _csrf tokens in the Ajax requests when we protect our application URL and application access using spring security.
How to get CSRF tokens
While we submit a form using an application that is protected with Spring Security, the form gets a default hidden parameter in the form body when using <form:form> element. The param contains the _csrf tokens to authenticate the requests in the server. In case we use other ways to create forms, we have to manually include a hidden parameter that contains name as ${_csrf.parameterName} and value as ${_csrf.token}. For example,
Ajax Requests
While we need to send ajax requests in an application that is protected with Spring Security, you will most likely find 403 error in the response from the server. This is due to the fact that the server expects a _csrf token that is missing in the XHR. How do we send csrf tokens in the ajax request so the server is happy to regard our request legitimate and help us with the response we need? Well, there are two ways we can do.
Generate CSRF Tokens
Spring security provides specific taglib that we can use to generate the CSRF tokens for sending them in the XHR requests.
How to get CSRF tokens
While we submit a form using an application that is protected with Spring Security, the form gets a default hidden parameter in the form body when using <form:form> element. The param contains the _csrf tokens to authenticate the requests in the server. In case we use other ways to create forms, we have to manually include a hidden parameter that contains name as ${_csrf.parameterName} and value as ${_csrf.token}. For example,
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/
Ajax Requests
While we need to send ajax requests in an application that is protected with Spring Security, you will most likely find 403 error in the response from the server. This is due to the fact that the server expects a _csrf token that is missing in the XHR. How do we send csrf tokens in the ajax request so the server is happy to regard our request legitimate and help us with the response we need? Well, there are two ways we can do.
- Generate csrf token header using spring security and set it in the ajax header.
- Generate csrf token using spring security and send them in the ajax request either via GET or POST.
Generate CSRF Tokens
Spring security provides specific taglib that we can use to generate the CSRF tokens for sending them in the XHR requests.
<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
The tag provides so many features that cater to security requirements. One of the usages of the taglib is to generate the metatags in the header. <sec:csrfMetaTags />
This will generate meta tags that are shown as below.<meta name="_csrf_parameter" content="_csrf" />
<meta name="_csrf_header" content="X-CSRF-TOKEN" />
<meta name="_csrf" content="897dc174-8aac-44be-bf63-7395bcac87f2" />
The above well fits into if we use taglibs and JSPs. But for those who prefer to use other templates like Thymeleaf, the csrf tokens can be obtained using the approach explained in the `How to get CSRF tokens`.CSRF token or Header?
Depending on the use case, we can set the CSRF token header or just CSRF token. For both GET or POST method, we can exploit the header approach to set the CSRF token header. But in case we need the CSRF token in the request param or request body, we can use just CSRF token. The below approach is based on setting it in the header so it fits for any requests. Assuming we have spring security metatags,
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
we create variables like these from meta tag content. And we set them in the header like below.$('.editable-action').editable({ type : 'select', source : MAKINUSCV.baseURL + '/admin/user/list/action.mk', url : MAKINUSCV.baseURL + '/admin/user/list/do/action.mk', ajaxOptions: { beforeSend: function (xhr) { xhr.setRequestHeader(csrfHeader, csrfToken); } }, success : function(response, newValue) { if (response.status == 'error') return response.msg; } });
In case we need to set in the request param or request body, we will be creating a data object in which we will set CSRF token. In that case, we will want to use the _csrf_parameter variable, not _csrf_header.
var csrfParam = $("meta[name='_csrf_parameter']").attr("content"); var data = {}; data[csrfParam] = csrfToken;And pass the data object to ajax request. If its GET request, just append the csrfParam and csrfToken in the url request.
Very good ideas and this was very useful for my professional oriented. Thanks for you provides a great post and I expect to you more information. Your written style is very impressed to me and I'm waiting for your updates...
ReplyDeleteSpoken English Classes in Chennai
Best Spoken English Classes in Chennai
Html5 Training in Chennai
IELTS Coaching in Chennai
Pega Training in Chennai
Japanese Classes in Chennai
TOEFL Coaching in Chennai
Spoken English Classes in Porur
Spoken English Classes in Anna Nagar
Thanks for publishing this blog. really good. Only professional can do this.
ReplyDeleteSpring Training in Chennai
Core Spring Training
Spring Training in Adyar
Hibernate Training in Chennai
Spring and Hibernate Training
soft skills training in chennai
core java training in chennai
Spring Training in Chennai
Really nice blog,i enjoyed your infomations. Thank you and i will expect more in future.
ReplyDeleteJAVA Training in Chennai
JAVA Training in Velachery
Software testing training in chennai
Android Training in Chennai
Selenium Training in Chennai
Big data training in chennai
JAVA Training in Chennai
Java Training in Tnagar
This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
ReplyDeleteAviation Academy in Chennai
Air hostess training in Chennai
Airport management courses in Chennai
Ground staff training in Chennai
aviation training in Chennai
air hostess academy in Chennai
Airport Management Training in Chennai
airport ground staff training courses in Chennai
Great job. Keep updating this article by posting new informations.
ReplyDeleteSpoken English Classes in Chennai
English Coaching Classes in Chennai
Japanese Language Classes in Chennai
French Language Classes in Chennai
pearson vue exam centers in chennai
German Classes in Chennai
Spoken English Classes in Tnagar
Spoken English Classes in OMR
Nice post with lots of information keep up the good work
ReplyDeletePython Course | Digital Marketing Course | Java Course
Nice post and more informative,thanks for sharing.
ReplyDeletefilm making courses in chennai
part time film making courses in chennai
film academy in chennai
acting institute in chennai
film studies in chennai
film making courses in chennai
direction course in chennai
This article is a very interesting and brief explanation about this topic. I eagerly waiting for your next post...
ReplyDeleteSpark Training in Chennai
Spark Training Academy
Oracle Training in Chennai
Excel Training in Chennai
Oracle DBA Training in Chennai
Embedded System Course Chennai
Tableau Training in Chennai
Unix Training in Chennai
Power BI Training in Chennai
Social Media Marketing Courses in Chennai
Thanks for this kind of worthy information. this was really very helpful to me. keep continuing.
ReplyDeleteEducation Franchise India
Spoken English Franchise
Franchise For Spoken English Classes
Top Education Franchise In India
Best Education Franchise In India
Computer Education Franchise
Education Franchise India
Computer Center Franchise
Education Franchise Opportunities In India
The article is so informative. This is more helpful for our
ReplyDeletebest software testing training in chennai
best software testing training institute in chennai with placement
software testing training
courses
software testing training and placement
software testing training online
software testing class
software testing classes in chennai
best software testing courses in chennai
automation testing courses in chennai
Thanks for sharing.
Thanks for posting this information. Keep updating.
ReplyDeleteSpoken English Classes in Chennai
Spoken English in Chennai
German Classes in Chennai
Japanese Classes in Chennai
TOEFL Coaching in Chennai
Informatica Training in Chennai
spanish language in chennai
content writing training in chennai
Spoken English Classes in Adyar
Spoken English Classes in Velachery
ReplyDeletePopular Fashion Blogs in Surat
Fashion Blogger in Surat
Surat Blogger
Indian Fashion Blogger
Great Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteProject Centers in Chennai
Java Training in Chennai
Final Year Project Domains for IT
Java Training in Chennai
Thanks for sharing information. Choosing computer accessories from leading IT store offer great discount and value for your money Computer Store Australia | All in One Pc Australia
ReplyDeleteIt is an excellent blog. Your post is very good and unique.
ReplyDeleteDevOps Training in Bangalore
DevOps Training in Marathahalli
Best DevOps Training in Marathahalli
DevOps Training Institutes in Marathahalli
DevOps Institute in Marathahalli
DevOps certification in Chennai
DevOps course in Chennai
Best DevOps Training in Chennai
DOT NET Training in Bangalore
PHP Training in Bangalore
It's remarkable. The way you describe the information is awesome. This will really help me out. Thanks for sharing.
ReplyDeleteVMware Training in Chennai
VMware Course in Chennai
Vmware Training center in Chennai
Vmware Learning
VMware Training
Vmware cloud certification
Enroll for selenium with python online training and you know how easy it is
ReplyDeleteIncredible post I should say and a debt of gratitude is in order for the data. Schooling is certainly a tacky subject. Be that as it may, is still among the main subjects within recent memory. I appreciate your post and anticipate more. You have made some valid statements there. I looked on the web to study the issue and discovered a great many people will oblige your perspectives on this site...
ReplyDeletepaper airplane that flies far and straight | windfin | stable paper airplane | nakamura paper airplane | paper airplane templates for distance | paper airplane designs