Working with OAuth and similar authentication protocols requires the use of temporary tokens which represent unique handshakes between multiple web services. These tokens must be unique, securely stored, and the longer, the better.
使用OAuth和类似的身份验证协议需要使用临时令牌,这些令牌代表多个Web服务之间的唯一握手。 这些令牌必须是唯一的,安全存储的,并且越长越好。
Since I've been out of the PHP game for a while, I was researching how to create such tokens without additional libraries. The following snippet does the trick:
由于我已经退出PHP游戏已有一段时间了,因此我正在研究如何在不使用其他库的情况下创建此类令牌。 以下代码片段可以解决问题:
// bin2hex(random_bytes($length))
$token = bin2hex(random_bytes(64));
/*
Examples:
39e9289a5b8328ecc4286da11076748716c41ec7fb94839a689f7dac5cdf5ba8bdc9a9acdc95b95245f80a00d58c9575c203ceb541507cce40dd5a96e9399f4a
1c46538c712e9b5bf0fe43d692147004f617b494d004e29daaf33e4528f253db5d911a690856f0b77cfa98103c8231bffff869f179125d17d28e52bfadb9f205
...
*/
If you aren't using PHP7 or above, you can fallback to the following:
如果您未使用PHP7或更高版本,则可以回退至以下内容:
$token = bin2hex(openssl_random_pseudo_bytes(64));
Having the backing of OpenSSL for token generation gives confidence that the token will be unique. Of course you can also do a storage check to ensure the token isn't already in use, but if you use a length of 64 or larger, the chances you repeat a token are incredibly slim!
拥有用于令牌生成的OpenSSL的支持,使人们确信令牌将是唯一的。 当然,您也可以进行存储检查以确保令牌尚未使用,但是如果您使用长度为64或更大的令牌,则重复令牌的机会非常小!