[英]token based authentication in php
我的網絡服務器上有一個REST服務,用php編寫。 我想知道,什么是最好的身份驗證(除了基本的http訪問身份驗證)。 我聽說過基於令牌的身份證,並且想問一下是否有人可以解釋主要步驟。
客戶端:Android /瀏覽器; 服務器:Apache,PHP5
它可以以任何一種方式完成,並且GET請求中的值實際上不比POST請求中的值更明顯。 如果有人可以“看到”(即攔截 )請求,他可以看到你發送的所有內容。 最后,HTTP請求只是一堆HTTP頭,可能后跟一個正文。 URL在第一個GET /foo/bar HTTP/1.1
行發送,其他值只是在不同的行中發送。
因此,您可以在何處發送您的身份驗證令牌。 您可以要求它是附加到每個請求的查詢參數:
GET /foo/bar?user=123456&token=abcde...
要真正按照預期使用HTTP協議,您應該使用Authorization
HTTP標頭:
Authorization: MyScheme 123456:abcde...
此標題的內容完全取決於您。 它通常指定一個像Basic
這樣的授權方法,然后是您想要進行身份驗證的任何方法。 這可以簡單地是用戶名和密碼,它們的哈希值,客戶端在某些時候或其他任何地方獲得的不透明令牌。
我建議使用令牌系統或請求簽名系統,后者非常受歡迎。 在請求簽名系統中,客戶端必須從您那里獲取令牌。 然后,它發送此令牌的散列和請求的某些特征以驗證請求,例如sha1(Token + Timestamp + Request URL + Request Body)
。 您的服務器可以驗證這一點,而客戶端不必在每個請求上以純文本形式發送令牌。
如何使令牌僅在特定時間有效?
您使用到期時間戳保存令牌服務器端並檢查它。
您可以使用基於Firefox的JWT(JSON Web令牌)進行基於令牌的身份驗證。
1)通過運行composer命令composer require firebase / php-jwt來安裝php jwt
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
define('SECRET_KEY','Your-Secret-Key') // secret key can be a random string and keep in secret from anyone
define('ALGORITHM','HS512')
之后生成您的令牌
$tokenId = base64_encode(mcrypt_create_iv(32));
$issuedAt = time();
$notBefore = $issuedAt + 10; //Adding 10 seconds
$expire = $notBefore + 7200; // Adding 60 seconds
$serverName = 'http://localhost/php-json/'; /// set your domain name
/*
* Create the token as an array
*/
$data = [
'iat' => $issuedAt, // Issued at: time when the token was generated
'jti' => $tokenId, // Json Token Id: an unique identifier for the token
'iss' => $serverName, // Issuer
'nbf' => $notBefore, // Not before
'exp' => $expire, // Expire
'data' => [ // Data related to the logged user you can set your required data
'id' => "set your current logged user-id", // id from the users table
'name' => "logged user name", // name
]
];
$secretKey = base64_decode(SECRET_KEY);
/// Here we will transform this array into JWT:
$jwt = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
ALGORITHM
);
$unencodedArray = ['jwt' => $jwt];
將此令牌提供給您的用戶“ $ jwt ”。 在每個請求中,用戶需要使用每個請求發送令牌值以驗證用戶。
try {
$secretKey = base64_decode(SECRET_KEY);
$DecodedDataArray = JWT::decode($_REQUEST['tokVal'], $secretKey, array(ALGORITHM));
echo "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();
} catch (Exception $e) {
echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.