Skip to content

CSRF Protection

StefansArya edited this page Apr 21, 2019 · 3 revisions

CSRF Protection is important to protect user from unexpected request because the user was redirected from malicious website to your API access. For the example you have an API for sending money and it's doesn't have CORS for it, the malicious website will redirect your user and bringing valid data to your API and it's getting processed because the user session on the cookies are valid.

That's why you will need to put CSRFToken for every request that need to be secured and validate it on the server. The CSRF token is containing a-z, A-Z, 0-9, and symbols, it has around 90 character sample and would be combined into 30~40 character. It would be difficult to be guessed.

You may need to import this feature on top of your code.

use \Scarlets\Library\CSRF;

Obtaining token for current user session

When you're using CSRF library, the User\Session will automatically being initialized.
The example below can be used if you want to make an internal API request, but it should be sent either as

  • POST query CSRFToken=xx
  • HTTP header CSRFToken: xx
<input id="CSRFToken" type="hidden" value="<?= $csrf::$token ?>">
<script>
    $.ajax({
        url: "/api/chat",
        data: { message:'hello' },
        type: "GET",
        beforeSend: function(xhr){
            xhr.setRequestHeader('CSRFToken', CSRFToken.value);
        },
        success: function(){alert('Success!');}
    });
</script>

Create hidden input for form data

The $csrf is also available when you serving with Serve::view.

<form method="POST" action="/message/post">
   <input name="message" type="text">
   <?= $csrf::hiddenInput() ?>
</form>

Validating CSRF token

Before processing the request data, you should check if the CSRF Token is valid.
If you want to use the user session for accessing API, this should be checked before any process.

if(CSRF::isRequestValid() === false)
   die("We can't validate your request");

Regenerate CSRF token

Usually we just need to generate the token one time, but if you don't like to reuse same token for every validation you can regenerate it. When you regenerate the token, it would consume a little resource to update your client's cookie and old CSRF token will be invalidated.

if(CSRF::isRequestValid() === true)
    CSRF::regenerate();

Clone this wiki locally