L
L
Lu_den2015-02-26 15:02:55
PHP
Lu_den, 2015-02-26 15:02:55

Why hash the string for cookies during authorization?

I read habrahabr.ru/post/13726 (instructions for creating an authorization system).

During authorization, the login and password are compared, if they are correct, then a random string is generated, which is hashed and added to the database in the user_hash string. In the user's cookies, we write down his unique identifier and the generated hash.

I can not understand what is the point of hashing a string that will go into cookies. This is not a password that the user enters in clear text and which needs to be compared with the hash stored in the database. Here the hash is compared to the hash:
// Скрипт проверки
# Соединямся с БД
mysql_connect("localhost", "myhost", "myhost");
mysql_select_db("testtable");
if (isset($_COOKIE['id']) and isset($_COOKIE['hash']))
{   
    $query = mysql_query("SELECT *,INET_NTOA(user_ip) FROM users WHERE user_id = '".intval($_COOKIE['id'])."' LIMIT 1");
    $userdata = mysql_fetch_assoc($query);
    if(($userdata['user_hash'] !== $_COOKIE['hash']) or ($userdata['user_id'] !== $_COOKIE['id'])
 or (($userdata['user_ip'] !== $_SERVER['REMOTE_ADDR'])  and ($userdata['user_ip'] !== "0")))
    {
        setcookie("id", "", time() - 3600*24*30*12, "/");
        setcookie("hash", "", time() - 3600*24*30*12, "/");
        print "Хм, что-то не получилось";
    }
    else
    {
        print "Привет, ".$userdata['user_login'].". Всё работает!";
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Safronov, 2015-02-26
@mcdb

Absolutely pointless waste of resources. You don't even need to put it in cookies. Store only the user ID in the cookie. If it is there, then the user has entered the site and everything is fine.
After all, no one will pick up a permanent user ID, it's not some kind of unnecessary meaningless hash generated with each login.

H
He11ion, 2015-02-26
@He11ion

Article of 2007, in the yard of 2015 - better not read this.
And it is written, probably, "for security".

K
Kirill Vasiliev, 2015-03-07
@vasilevkirill

If the hash exists in the database during authorization, then you can write this hash into the cookie.
In each script where it is necessary to check the validity of authorization, you check what is in the cookie and in the database, if there are a lot of requests, then you can set the check time through the session (every 5 minutes).
with this approach, you will have the following functionality.
you can throw off the user's authorization by simply changing the hash in the database.
In cookies, you do not store real information but a password.
also with this approach, you can make authorizations only on one client!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question