TOKEN
概念: 令牌,就是加密的字符串, 是訪問資源的憑證。Token需要查庫驗證token 是否有效。
- 客戶端使用用戶名跟密碼請求登錄。
- 服務端收到請求,去驗證用戶名與密碼。
- 驗證成功,服務端會簽發一個Token保存到(Session,redis,mysql…)中,然後再把這個 Token 發送給客戶端。
- 客戶端收到 Token 以後可以把它存儲起來,比如放在 Cookie 裏或者 Local Storage 裏。
- 客戶端每次向服務端請求資源的時候需要帶着服務端簽發的 Token。
- 服務端收到請求,驗證密客戶端請求裏面帶着的Token和服務器中保存的Token進行對比效驗, 如果驗證成功,就向客戶端返回請求的數據。
JWT
JWT是json web token縮寫。它將用戶信息加密到token裏,服務器不保存任何用戶信息。服務器通過使用保存的密鑰驗證token的正確性,只要正確即通過驗證。
JWT不用查庫,直接在服務端進行校驗,因爲用戶的信息及加密信息,和過期時間,都在JWT裏,只要在服務端進行校驗就行,並且校驗也是JWT自己實現的。
JWT包含三個部分: Header頭部,Payload負載和Signature簽名。由三部分生成JwtToken,三部分之間用“.”號做分割。 校驗也是JWT內部自己實現的 ,並且可以將你存儲時候的信息從JwtToken中取出來無須查庫。
- 客戶端使用用戶名跟密碼請求登錄。
- 服務端收到請求,去驗證用戶名與密碼。
- 驗證成功,服務端會簽發一個JwtToken,無須存儲到服務器,直接再把這個JwtToken發送給客戶端。
- 客戶端收到JwtToken以後可以把它存儲起來,比如放在 Cookie 裏或者 Local Storage 裏。
- 客戶端每次向服務端請求資源的時候需要帶着服務端簽發的JwtToken。
- 服務端收到請求,驗證密客戶端請求裏面帶着的 JwtToken, 如果驗證成功,就向客戶端返回請求的數據。
安裝
composer require firebase/php-jwt
使用
加密
$key = 'example_key';
$payload = [
'iss' => 'http://example.org',
'aud' => 'http://example.com',
'iat' => 1356999524,
'nbf' => 1357000000,
'jti' => [
'id' => 1,
'type' => 'test'
]
];
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
$jwt = JWT::encode($payload, $key, 'HS256');
解析
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
print_r($decoded);
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
/**
* You can add a leeway to account for when there is a clock skew times between
* the signing and verifying servers. It is recommended that this leeway should
* not be bigger than a few minutes.
*
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
*/
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
print_r($decoded);