L
L
leetnigga2016-05-02 00:12:45
PHP
leetnigga, 2016-05-02 00:12:45

How to properly authenticate in php?

Hello.
Actually, the question is simple: you need to make authentication on php. There is a table in the database with a login / password, there is a login page, there is a page where only logged in users should be allowed. Everything is as simple as possible, the login is only for the current session, the "Remember me" button is not needed.
My knowledge of this ends with the book “PHP for Beginners” of 2005, where it is done like this: if the login and password are correct, then a session is created with the only variable in it user_id, which stores the user ID in the database or 0 if the user not logged in. It is also used to check access. But I have a suspicion that this is not entirely correct and not very safe.
I googled and looked at the Yii, Symphony, and PHPixie sources to see how smart people do authentication, but the code is too complicated for me to understand. Too many tokens, providers, domains and more.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2016-05-02
@leetnigga

After googling, I looked at the sources of Yii, Symphony and PHPixie to find out how smart people do authentication

Don't forget that in frameworks it's all done with one calculation - to cover 95% of possible use cases. And in this regard, the implementation is a little more complicated. Also, do not forget that all this "should" work on php5.4+, and, for example, the password api appeared only in 5.5, and password hashing is a whole science.
Let's decompose the task into sub-tasks:
We need to validate the data entered by the user. It can be a pair of identifier + some kind of secret key (email + password if it’s easier), or maybe it’s just a secret key (token), or a JWT token ... in a word, there are many options, but for now we need a couple of good old email + password .
To do this, PHP has a very easy-to-use api for working with passwords: password api. Only use it (or whatever uses it under the hood) because it's the safest and most reliable way to work with passwords in PHP. Be sure to read this section of the documentation.
In a very simple case (which is the majority), when registering, you just need to drive the line into password_hash and get a new line as output, which is written to the database. When logging in, we pick up the user with the specified email and check the entered password through the password_verify function.
Once we've made sure the user isn't impersonating another, we can create a session. In the simplest case, we simply create a session with a user ID and ... that's all. the session id will be written to the http-only cookie and everything is great. True, when working with sessions in PHP, you need to remember about CSRF attacks that you need to protect yourself from (which almost all frameworks can do out of the box).
Further, the mechanisms of authorization, that is, the differentiation of rights, can be simplified from a banal hierarchy of roles to a more complex system of waterers (a design pattern of a chain of responsibilities). Everything depends on the needs.
ps Since this question is very sensitive, and in order to make all this "safe" you need the order of experience, I recommend that you deal with frameworks or ready-made popular libraries.

I
index0h, 2016-05-02
@index0h

Try using the example from Symfony but with xdebug enabled. Go through the authentication process from the beginning of the request to the return of the response. In fact, xdebug should be used in principle for situations where you don't know what's going on in the code))

A
Alexander Litvinenko, 2016-05-02
@edli007

PHP for Beginners" 2005, where it is done like this: if the login and password are correct, then a session is created with the only variable in it user_id, which stores the user ID in the database or 0 if the user is not logged in. It is also used to check access. But I have a suspicion that this is not entirely correct and not very safe.

This book seems to be printed from an even older one.
1. in the database - id, login and hashed password.
2. some kind of uid in the session. If there is no uid in the session, the user is a guest.
how it interacts with each other is up to you.

F
Fairlancer, 2016-05-02
@kursorik2

I think that Sergey Protko chewed everything up enough, but I will give you a safe and simple code to make it clearer:

// Готовим запрос к базе данных ...
$pdo->$main->pdo_prepare("SELECT `*` FROM TABLE `xxx` WHERE login=`?` AND password= `?`");
// Готовим плейсхолдеры и формируем пейлоад.
$pdo->$main->pdo_append(array(html_real_escape($_REQUEST["login"]),html_real_escape($_REQUEST["password"])));
// Выполняем запрос в базу ...
$pdo->$main->pdo_execute();
// Читаем запрос из базы в виде ассоциативного массива...
$pdo->$main->fetch_row();
if($row["login"] == $_REQUEST["login"]) {
echo "Пользователь прошёл проверку, доступ разрешён.";
} esle {
echo " Пользователь не прошёл проверку. ";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question