Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security CSRF CORS

Problem Statement: I have some restful APIs which are CSRF protected using spring security. Also, these APIs will be accessed from different Origin/domain by Angular WEB UI. I don't need Spring Authentication as authentication is handled by Siteminder.

Approach: I followed this link from from Dave Syer for CSRF protection : The Login Page: Angular JS and Spring Security Part II which is working perfectly except one issue (Below).

Issue: This code work perfectly fine when my angular html client accessing the RESTful APIs on the same origin/domain; but when I try to access the same APIs from a different origin, getting an error 403 - Access Forbidden - CSRF token error.

Approach That I tried so far by extending your example:

  1. Added a CORS filter - Enabling Cross Origin Requests for a RESTful Web Service

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    

No Luck on the above.

Please suggest if I need to do anything else to make it work.

Thanks, Suman

like image 626
Sum Avatar asked Jan 31 '26 09:01

Sum


1 Answers

CSRF and CORS are not the same thing. You probably have the CORS part sorted now, but you need to add a CSRF token to any POST/PUT/DELETE requests. Spring Security sends the token in a header in the blog series you quoted and Angular picks it up from there (you need to add a few lines of code to get that working).

like image 94
Dave Syer Avatar answered Feb 02 '26 04:02

Dave Syer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!