简体   繁体   中英

PHP - Is this secure enough for unique session tokens?

I am creating a PHP application and need user authentication to be as secure as possible!

Once the user has logged-in I need to set a cookie (along with other cookies) with a session identifier and this has to be unique.

<?php

// Set default timezone for time() function.
date_default_timezone_set("Europe/London");

$secure_token_length = 16; // 32-Digits Long.

// Generate unique token.
$token = time() . "-" . bin2hex(openssl_random_pseudo_bytes($secure_token_length, $strong));

// Set session identifier.
setcookie("session", $token, 0, "/app/", false, false, true);

?>

As you can see I'm creating a unique token and appending the current UNIX timestamp to ensure that this value is not generated twice, The secure token is stored in a database within a UNIQUE column and the token is not inserted into the database if it is already in use (Using PHP's Do-While function), Any advice on how to make this more secure please comment.

If you want it to be "secure as possible" then please use an established method rather than trying to create your own. For example, let a third-party authenticate for you just like StackOverflow allows you to login with Facebook, Yahoo, etc...

Additionally, PHP has built-in session handling functions which can work with both cookies and databases, OWASP has a guide on how to securely manage your sessions, I don't understand why you're trying to reinvent the wheel here by generating your own session tokens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM