我目前正在使用PHP构建RESTful API,它将用于为Web和移动应用程序提供支持。因此,API应该被视为公开的。但是,我想在用户从移动设备或网络发出API请求时对用户进行身份验证。
当用户注册该服务时,我会生成一个唯一的API密钥和密钥,该密钥和密钥是根据用户在数据库中的记录存储的。理想情况下,我希望使用JavaScript或PHP仅使用API密钥进行请求。
我考虑建立一个用于身份验证的握手系统,流程如下:
我正在考虑使用HMAC来生成令牌,如下所示:
$token = hash_hmac('sha256', $user->apiKey.microtime(), $user->apiSecret);
然后$token
将存储在数据库中,并且对于每个请求都应该是唯一的。然后,可以使用以下jQuery代码进行请求:
$.getJSON('/api/user/get/1', { 'key': '123rrwfnufsd7f72' }).done(function(data) {
// data will now contain a token, so we use it to make another AJAX request:
if( data.token )
{
$.getJSON('/api/user/get/1', { 'token': data.token }).done(function(user) {
// do something with user or handle bad token
});
}
});
我的问题是,这足以防止蛮力和重播攻击吗?
答案 0 :(得分:1)
我刚刚解决了一个关于这个的小lib。如果需要,您可以指定时间漂移(以分钟为单位),甚至可以使用自定义盐。 (见https://github.com/gboddin/psk-validator/)
此库允许您验证来自客户端的签名邮件 使用基于时间的盐。
composer require gboddin/psk-validator
$sharedsecret = '43223ff65b6ce17072cda5729b20daceec611d1f39e76040d347ceeca51d2a47';
$data = json_encode(['suff','otherstuff',['machin' => 'bidule']]);
/**
* Client :
* Invoke the validator with the pre-shared key and an algo (sha256 by default) and
* define an allowed time drift in minutes ( 2 by default ).
*/
$sigValidation = new \Gbo\PSKValidator($sharedsecret, 'sha256');
/**
* Signs a bunch of data and get the signature.
* The second optional parameters allows for a user provided salt instead
* of the default time based salt. It must be agreed on between client and server.
*/
$signature = $sigValidation->sign($data, null);
/**
* Server :
* The optional third parameter allows to define a maximum time drift in minutes ( default 2 minutes )
*/
$signature = $httpRequest->getHeader('x-signature');
$sharedsecret = '43223ff65b6ce17072cda5729b20daceec611d1f39e76040d347ceeca51d2a47';
$sigValidation = new \PSKValidator($sharedsecret, 'sha256', 2);
$data = $httpRequest->getBody();
/**
* Server :
* The third optional parameters allows for a user provided salt instead
* of the default time based salt. It must be agreed on between client and server.
*/
$signatureIsValid = $sigValidation->verify($data, $signature, null);
var_dump(
$data,
$signature,
$sigValidation->getTimeBasedSignatures($data),
$signatureIsValid
);
string(41) "["suff","otherstuff",{"machin":"bidule"}]"
string(64) "d85a2d6873e034cb3ab8c490cb82139d8dabae6c08581cca0a2e7497ead287a4"
array(5) {
[0]=>
string(64) "d85a2d6873e034cb3ab8c490cb82139d8dabae6c08581cca0a2e7497ead287a4"
[1]=>
string(64) "dc150239c61fe272b7ca44ad0918d159a84e5bc1661db48bad04a81bc7f4c742"
[2]=>
string(64) "e1822fc6cc7bbf1184b29efaaaceac6d598fb406b4f8cf9b3717b3d0c533c19f"
[3]=>
string(64) "d85a2d6873e034cb3ab8c490cb82139d8dabae6c08581cca0a2e7497ead287a4"
[4]=>
string(64) "d85a2d6873e034cb3ab8c490cb82139d8dabae6c08581cca0a2e7497ead287a4"
}
bool(true)
(对不起自我宣传:))