I have a question about tokens. I understand that they are random characters used for security purposes but just how do they work and what do they protect against?
2
-
The tokens are added for protecting the Cross-site_request_forgery, also this is not only way to attact, there are sql injection, XSS ,en.wikipedia.org/wiki/Cross-site_request_forgery. Also one php implementation csrf.htmlpurifier.orgRisto Novik– Risto Novik2012-02-21 07:15:58 +00:00Commented Feb 21, 2012 at 7:15
-
Can you show me an example of tokens in PHP and how they can be used?Kevin Oluseun Karimu– Kevin Oluseun Karimu2012-02-21 07:24:05 +00:00Commented Feb 21, 2012 at 7:24
Add a comment
|
1 Answer
Authentification mechanism creates a token when form displayed, and was stored it on server side. Also auth mechanism adds token as hidden input to form. When you send it, auth system check is it in server-side storage. If token found, authentification process will continue and token was removing.
It protects from spamming form action script.
Example using with logout url:
<?php
// Generate token
$logout_token = md5(microtime().random(100, 999));
session_start();
// Store token in session
if (!is_array($_SESSION['logout_tokens']) {
$_SESSION['logout_tokens'] = array();
}
$_SESSION['logout_tokens'][] = $logout_token;
?>
<a href="/logout/?logout_token=<?= $logout_token ?>">logout</a>
Script, that processing logout:
<?php
$done = false;
if (!empty($_GET['logout_token'])) {
// Get token from url
$logout_token = $_GET['logout_token'];
session_start();
if (!is_array($_SESSION['logout_tokens']) {
$_SESSION['logout_tokens'] = array();
}
// Search get token in session (server-side storage)
if (($key = array_search($logout_token, $_SESSION['logout_tokens'], true)) !== false) {
// Remove used token from storage
unset($_SESSION['logout_tokens'][$key]);
// Do logout
$done = true;
}
}
if ($done === false) {
echo "Something went wrong.";
}
3 Comments
Kevin Oluseun Karimu
What about when tokens are passed as a URL parameter. How does that work?
Electronick
token used to validate request. It can be created on server side, or from request params. But if you want good protection you should hide token generation mechanism from others. It can be passed any way that server can read.
Kevin Oluseun Karimu
So can you show me an example of how it would work when it is used as a url parameter. Example: example.com/logout.php?hash=6556jhntrh67&logout=true