Cross-Site Request Forgery (CSRF) is a type of web application vulnerability in which an attacker coerces a user to issue requests via a browser that is already logged into an application. The user may not be aware of what the browser is sending to the server, but the server trusts the request because the user is authenticated. In LabKey, all POST requests will enforce CSRF protection. Any POST that fails to include a CSRF token will fail.
This topic helps you understand how you can obtain a CSRF token using the API.
Extract Token From Cookie
In this first example, a wiki can include code that extract a user's CSRF token from the cookie stored on the user's machine. In this example, the "create_new_experiment_form" wiki will fetch the CSRF token from the cookie and pass it with the request to create the new experiment.
Example Code
<form id="create_new_experiment_form" action="/myfolder/experiments/insertExperiment.view?query.Description~isnonblank=&returnUrl=%2Fmyfolder%2Fexperiments%2Fbegin.view" method="POST">
<input type="hidden" id="CSRFToken" name="X-LABKEY-CSRF" value="" />
<a href="javascript:{}" onclick="document.getElementById('create_new_experiment_form').submit(); return false;">Create new experiment</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
function getCSRFToken() {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, 14) == ('X-LABKEY-CSRF' + '=')) {
cookieValue = decodeURIComponent(cookie.substring(14));
break;
}
}
}
return cookieValue;
}
document.getElementById('CSRFToken').value = getCSRFToken();
</script>
Call LABKEY.CSRF
LabKey provides a built in utility for this purpose, making it even simpler to fetch the CSRF token for a successful POST using the API:
Example Code
<form id="create_new_experiment_form" action="/myfolder/experiments/insertExperiment.view?query.Description~isnonblank=&returnUrl=%2Fmyfolder%2Fexperiments%2Fbegin.view" method="POST">
<input type="hidden" id="CSRFToken" name="X-LABKEY-CSRF" value="" />
<a href="javascript:{}" onclick="document.getElementById('create_new_experiment_form').submit(); return false;">Create new experiment</a>
<script>
document.getElementById('CSRFToken').value = LABKEY.CSRF;
</script>
Related Topics