0

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.org Commented Feb 21, 2012 at 7:15
  • Can you show me an example of tokens in PHP and how they can be used? Commented Feb 21, 2012 at 7:24

1 Answer 1

1

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.";
}
Sign up to request clarification or add additional context in comments.

3 Comments

What about when tokens are passed as a URL parameter. How does that work?
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.