{"id":3964,"date":"2020-10-03T07:36:18","date_gmt":"2020-10-03T07:36:18","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=3964"},"modified":"2020-10-04T04:35:59","modified_gmt":"2020-10-04T04:35:59","slug":"how-csrf-works-in-spring-security","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/how-csrf-works-in-spring-security\/","title":{"rendered":"How CSRF works in Spring Security"},"content":{"rendered":"<ol>\n<li>CSRF Refers to Cross Site Request Forgery. More on CSRF Here<\/li>\n<li>When the Client makes the first GET request to the Server, Server generates CSRF token and sends back to Client<\/li>\n<li>On the Subsequent PUT,POST and DELETE request from the Client this token would be used for Authentication<\/li>\n<li>In Postman for the Same reason GET request would work irrespect we disable the CSRF in protected void configure(HttpSecurity httpSecurity) method. But for the PUT,POST and DELETE we should disable the CSRF as below otherwise the server would expect CSRF token when the request to server is PUT,POST and DELETE.\n<pre>\r\n@Override\r\nprotected void configure(HttpSecurity httpSecurity) throws Exception\r\n{\r\n\r\nhttpSecurity.csrf().disable()\r\n            .authorizeRequests()\r\n            .antMatchers(\"\/\", \"index\", \"\/css\/*\", \"\/js\/*\").permitAll()\r\n            .\r\n            . \r\n<\/pre>\n<\/li>\n<\/ol>\n<p><img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/CSRF-Token.jpg\" alt=\"\" \/><\/p>\n<p><strong class=\"cta3Header\">Using CSRF Token for Authorization<\/strong><\/p>\n<ol>\n<li>We have set of API&#8217;s exposed to the users whose role is ADMIN<\/li>\n<li>The way CSRF works is first Token would be generated once the User Logins using UserID and Password. The Way it works in REST API is first time<br \/>\nwhen you use GET method you should use Basic Auth in Authorization to Generate <strong>XSRF-TOKEN<\/strong> which would be set in Cookie along with <strong>JSessionID <\/strong>and also available in <strong>Response Headers<\/strong><\/li>\n<li>By default CSRF is not applicable for GET unless it is pointed to resource API. Simple reason behind that is, when the user types URL of login thats the first page which take login. If you try to access <em>http:\/\/localhost:8080\/<\/em> in postman it works fine without CSRF but when you access <em>http:\/\/localhost:8080\/api\/v1\/students\/<\/em> which again uses GET method but points to resource API then it asks for UserId and Password due to basic Auth<\/li>\n<li>Subsequent POST, PUT and DELETE request could be done by attaching <strong>X-XSRF-TOKEN<\/strong> to header. The Cookie which has the JSESSIONID and XSRF-TOKEN should not be deleted in Postman<\/li>\n<li>Though CSRF is enabled explicity in my Code it didnt worked until i added following lines in ApplicationSecurityConfig.java\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n.\r\n.\r\n        httpSecurity\r\n                     .csrf()\r\n                     .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())\r\n.\r\n<\/pre>\n<\/li>\n<\/ol>\n<p><strong>Accessing resource using GET (No Authentication or Authorization) <\/strong><br \/>\n<img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/SimpleGetwithoutCSRF.jpg\" alt=\"\" \/><\/p>\n<p><strong>Accessing resource using GET (Authentication needed for API Resource) <\/strong><br \/>\n<img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/CSRFinRespHeader.jpg\" alt=\"\" \/><\/p>\n<p><strong>Accessing resource using POST (X-XSRF-TOKEN) in request header<\/strong><br \/>\n<img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/CSRFPost.jpg\" alt=\"\" \/><\/p>\n<p><strong>XSRF-TOKEN received after GET with credentials and X-XSRF-TOKEN in haeder for sunsequent POST,PUT and DELETE calls  <\/strong><br \/>\n<img decoding=\"async\" src=\"https:\/\/codethataint.com\/blog\/wp-content\/uploads\/2020\/10\/Capture11.jpg\" alt=\"\" \/><\/p>\n<p><strong>ApplicationSecurityConfig.java<\/strong><br \/>\n<em>Using CSRF Token for Authorization<\/em><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n@Override\r\n    protected void configure(HttpSecurity httpSecurity) throws Exception{\r\n        httpSecurity\r\n                     .csrf()\r\n                     .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())\r\n                     .and()\r\n                    .authorizeRequests()\r\n                    .antMatchers(&quot;\/&quot;, &quot;index&quot;, &quot;\/css\/*&quot;, &quot;\/js\/*&quot;).permitAll()\r\n                    .antMatchers(&quot;\/api\/**&quot;).hasRole(&quot;ADMIN&quot;)\r\n                    .anyRequest()\r\n                    .authenticated()\r\n                    .and()\r\n                    .httpBasic();\r\n}\r\n<\/pre>\n<p><strong>FAQ<\/strong><br \/>\nThere are N number of possibilities. Try out in Postman.<\/p>\n<ol>\n<li><strong>How GET method to API resource Works with out CSRF token?<\/strong><br \/>\nIt works based on JSESSIONID. When the JSESSIONID in cookie is deleted then again it asks for Login and password\n<\/li>\n<li><strong>What happens when I delete XSRF token in Cookie?<\/strong><br \/>\nNew Token would be generated based on JSESSIONID in cookie\n<\/li>\n<li><strong>What happens when I delete XSRF token and in Cookie and try POST, DELETE and PUT over API?<\/strong><br \/>\nNew JSESSIONID would be generated and placed in cookie. For this X-XSRF-TOKEN should be passed in header.\n<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>CSRF Refers to Cross Site Request Forgery. More on CSRF Here When the Client makes the first GET request to the Server, Server generates CSRF token and sends back to Client On the Subsequent PUT,POST and DELETE request from the Client this token would be used for Authentication In Postman for the Same reason GET&hellip; <a href=\"https:\/\/codethataint.com\/blog\/how-csrf-works-in-spring-security\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3964","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3964","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=3964"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3964\/revisions"}],"predecessor-version":[{"id":3977,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3964\/revisions\/3977"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=3964"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=3964"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=3964"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}