-
Notifications
You must be signed in to change notification settings - Fork 0
07. CSRF Protection
Dzyanis Sukhanitski edited this page Feb 28, 2023
·
4 revisions
Videna framework uses two types of Cross-Site Request Forgery (CSRF) protection:
- synchronizer token pattern - framework automatically generates a "token" for each active user session. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it.
-
double submit cookies pattern - framework automatically generates a "csrf_token" token to save it in cookies. Therefore you must provide the value of the CSRF token for unsecure request methods: "POST", "PATCH", "DELETE" and "PUT" methods for
AppController
and "POST" method forHttpController
.
For each request where parameters should be sent to the server you need to use one of the next options to provide "csrf_token":
- Add token parameter in GET request:
"csrf_token=<?= $csrf->token ?>"
- Add a hidden 'input' field in the HTML form for POST requests:
<input type="hidden" name="csrf_token" value="<?= $csrf->token ?>">
or simply:
<?= $csrf->input ?>
- Add JSON property in data request:
data: {
"csrf_token": "<?= $csrf->token ?>"
}
or simply:
data: {
<?= $csrf->json ?>
}
You could, for example, store the token in an HTML meta tag:
<meta name="csrf_token" content="<?= $csrf->token ?>">
or simply:
<?= $crsf->meta ?>
To get token value from the META tag you can use, for example, the next way:
const csrf_token = document.querySelector('meta[name="csrf_token"]').getAttribute("content");
or with jQuery:
const csrf_token = $('meta[name="csrf_token"]').attr('content');
file /App/configs/routs.php
:
use \Videna\Core\Route;
...
Route::get('/webapp/privacy-policy', 'WebApp@PrivacyPolicy');
file /App/Controllers/WebApp.php
:
use \Videna\Core\View;
...
public function actionPrivacyPolicy()
{
View::set([
'html' => View::render('/webapp/privacy-policy.php')
]);
}
file /Views/inc/header.php
:
<head>
<?= $csrf->meta ?>
...
file /Views/inc/footer.php
:
<div id="privacy-body"></div>
...
<script>
const getModalBody = async () => {
const data = JSON.stringify({<?= $csrf->json ?>});
try {
const response = await fetch('/webapp/privacy-policy', {
method: 'GET',
body: data,
headers: {
'Content-type': 'application/json'
}
});
if (response.ok) {
const jsonResponse = await response.json();
document.getElementById('privacy-body').innerHTML = jsonResponse.html;
}
}
catch (error) {
console.log(error);
}
}
getModalBody();
</script>