REST and Slim 3 : why CSRF check failed with post

2019-08-25 06:23发布

问题:

I want to add a user with REST API on a web application created with Slim3. I use the same route on application to add a user and it's works. But by an ajax request since an other website I have "400 bad request" because of CSRF check failed. Before this request I do a GET method to get CSRF token and build hidden input with CSRF token data. Then I give CSRF token at POST method but it doesn't work... I don't understand.

Thanks.

Ajax Get Method :

$.get("https://extranet.exemple.fr/api/token", {})
            .done(function (data, text, jqxhr) {
                if (data.success === true) {
                    $("#csrf_name").val(data.csrf.csrf_name);
                    $("#csrf_value").val(data.csrf.csrf_value);
                }
            })
            .fail(function (jqxhr) {})
            .always(function () {});
            });

Ajax POST :

var csrfname = $("#csrf_name").val();
var csrfvalue = $("#csrf_value").val();
var objajaxargs = {
                    dataUser: dataUser,
                    csrf_name: csrfname,
                    csrf_value: csrfvalue,
                };
                $.post("https://extranet.exemple.fr/user/add", objajaxargs)
                    .done(function (data, text, jqxhr) {
                        if (data.success === true) {
                            alert("success");
                        }
                    })
                    .fail(function (jqxhr) {})
                    .always(function () {});

In my container

$container["csrf"] = function ($container) {
    return new \Slim\Csrf\Guard();
};

Slim GET method

$app->get('/api/token', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) use ($app) {

$container = $app->getContainer();
// Generate new token and update request
$request = $container->csrf->generateNewToken($request);
// Build Header Token
$nameKey = $container->csrf->getTokenNameKey();
$valueKey = $container->csrf->getTokenValueKey();
$name = $request->getAttribute($nameKey);
$value = $request->getAttribute($valueKey);
$tokenArray = [
    $nameKey => $name,
    $valueKey => $value
];

$respCSRF["success"] = false;
if (!empty($tokenArray)) {
    $respCSRF["success"] = true;
    $respCSRF["csrf"] = $tokenArray;
}

return $response->withJson($respCSRF);});

Slim POST method

$app->post("/user/add", function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) use ($app) {

$container = $app->getContainer();
$objBody = $request->getParsedBody();
$objUser = new \App\Models\UserModel($container);

foreach ($objBody["dataUser"] as $key => $value) {
    $objAdherent->$key = $value;
}

$arrJsonResponse = ["success" => false];

if (filter_var($objUser->mail, FILTER_VALIDATE_EMAIL) !== false) {
    $infosAdd = $objUser->addUser();
    if ($infosAdd !== false) {
        $arrJsonResponse["success"] = true;
        return $response->withJson($arrJsonResponse)->withStatus(201);
    }
} 

return $response->withJson($arrJsonResponse)->withStatus(400);});

回答1:

I resolve my problem. I set csrf token persistence at true and it's works!

Solution:

 /**
 * Init CSRF
 * @return \Slim\Csrf\Guard
 */
$container["csrf"] = function ($container) {
    $guard = new \Slim\Csrf\Guard();
    $guard->setPersistentTokenMode(true);
    return $guard;
};