A
A
Anton2020-04-10 21:13:45
PHP
Anton, 2020-04-10 21:13:45

CSRF token generation or other php options?

I have my own API on the site at site.com/api.php
In the frontend, on different pages there are a bunch of ajax handlers that access these APIs for any action. I need my API to accept some token in the POST request and compare it, if the token is correct, let the data be processed. But, how can I generate this token in api.php and on other pages so that it is identical. And yet, that this key could work in two tabs. I heard that $_SESSION['csrf_token'] is generated every time a new page is opened.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2020-04-10
Veida @aveyda7

You generate a random token, put it in the session / cache / database and send it to the page in some meta tag in the head, for example.
When sending a POST request, the front takes this token and sends it to the back.
Back checks for its availability and its expiration date. If the token was valid, then generate a new one in response and send it to the page again, if not, force the user to refresh the page. In both cases, the token is invalidated and removed.
Once every 10 / 100 / 1000 token checks, run the invalid token cleaner with expired validity.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question