Skip to content

Instantly share code, notes, and snippets.

@rtcoms
Created March 2, 2022 20:32
Show Gist options
  • Save rtcoms/2675502a26c5a2615d00903cbc2f28a5 to your computer and use it in GitHub Desktop.
Save rtcoms/2675502a26c5a2615d00903cbc2f28a5 to your computer and use it in GitHub Desktop.
# What is CSRF attack ?
Cross-Site Request Forgery is an attack where a third party from forges a request to
another site.
Here is an example of CSRF attack:
1. You visit site bad.com
2. bad.com has a hidden form that submit request to yourbacnk.com/transfer_credits. If you're logged on yourbank.com
then browser will attach the cookies associated even if request is made from bad.com. Application server will also process
the request and user will lose credits.
3. This will work even if you've enabled CORS (cross origin resource sharing) protection, because that just work at the response level.
# How CORS(Cross origin resource sharing) is not enough to resolve CSRF attacks ?
Many people assume that condifuring application server that setting CORS config can resolve completely, that not true though.
General configuration for CORS works at response level so user will not get response at client but request will be processed, and thus
CORD is not the solution for this
# How CSRF token tackle CSRF attack ?
With csrf token, application sets a csrf token as hidden input in the form,
when application received the post request, before processing it verifies the csrf token.
CSRF token are required mainly for HTML form based requests because CSRF attack is a cookie based attacks.
Since this csrf_token is a random value there is no way for hacker to know what the "csrf_token" is for my session.
And hacker will not be able to pass the correct "authenticity_token".
The check for CSRF in rails controller is enabled using `protect_from_forgery`
In Rails 5: csrf token for each form has been added, and a csrf token will be
valid only for the method/action of the form it was included in. This was required because a
hacker can nest a valid form inside another form
# Is CSRF required for API ?
CSRF attacks work based on cookies and so CSRF protection is not required for APIs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment