Json web token (JWT), an open JSON-based standard (RFC 7519) implemented to pass declarations between network application environments. The token is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios for distributed sites.
JWT statements are generally used to pass authenticated user identity information between the identity provider and the service provider to facilitate the acquisition of resources from the resource server. Some additional declaration information necessary for other business logic can also be added. The token can also be used for authentication or encrypted.

HMAC-SHA256(SecretKey, Base64UrlEncode(JWT-Header)+'.'+Base64UrlEncode(JWT-Payload))base64(header).base64(payload).signature as JWT token to return to the client.composer require tinywan/jwt use Tinywan Jwt JwtToken ;
$ user = [
' id ' => 2022 ,
' name ' => ' Tinywan ' ,
' email ' => ' [email protected] '
];
$ token = JwtToken:: generateToken ( $ user );
var_dump ( json_encode ( $ token ));Output (json format)
{
"token_type" : " Bearer " ,
"expires_in" : 36000 ,
"access_token" : " eyJ0eXAiOiJAUR-Gqtnk9LUPO8IDrLK7tjCwQZ7CI... " ,
"refresh_token" : " eyJ0eXAiOiJIEGkKprvcccccQvsTJaOyNy8yweZc... "
}Response parameters
| parameter | type | describe | Example Values |
|---|---|---|---|
| token_type | string | Token Type | Bearer |
| expires_in | int | The validity time of the voucher, unit: seconds | 36000 |
| access_token | string | Access credentials | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX |
| refresh_token | string | Refresh credentials (use of access credentials expired) | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX |
1. Get the current id
$ id = Tinywan Jwt JwtToken:: getCurrentId ();2. Get all fields
$ email = Tinywan Jwt JwtToken:: getExtend ();3. Get custom fields
$ email = Tinywan Jwt JwtToken:: getExtendVal ( ' email ' );4. Refresh token (get access token by refreshing token)
$ refreshToken = Tinywan Jwt JwtToken:: refreshToken ();5. The remaining time of the token validity period
$ exp = Tinywan Jwt JwtToken:: getTokenExp (); 6. Single device login. The default is off. Please modify the configuration file config/plugin/tinywan/jwt
' is_single_device ' => true,Single-device login supports defining
clientfields and customizing client single sign-on (default isWEB, that is, web page), such as:MOBILE,APP,WEB,ADMIN,API,OTHER, etc.
$ user = [
' id ' => 2022 ,
' name ' => ' Tinywan ' ,
' client ' => ' MOBILE ' ,
];
$ token = Tinywan Jwt JwtToken:: generateToken ( $ user );
var_dump ( json_encode ( $ token ));7. Obtain current user information (model)
$ user = Tinywan Jwt JwtToken:: getUser (); The configuration project 'user_model' is an anonymous function, which returns an empty array by default. You can customize your own return model according to your project ORM
ThinkORM configuration
' user_model ' => function ( $ uid ) {
// 返回一个数组
return think facade Db:: table ( ' resty_user ' )
-> field ( ' id,username,create_time ' )
-> where ( ' id ' , $ uid )
-> find ();
}LaravelORM configuration
' user_model ' => function ( $ uid ) {
// 返回一个对象
return support Db:: table ( ' resty_user ' )
-> where ( ' id ' , $ uid )
-> select ( ' id ' , ' email ' , ' mobile ' , ' create_time ' )
-> first ();
}8. Token cleaning
$ res = Tinywan Jwt JwtToken:: clear ();Only if the configuration item
is_single_deviceistruewill it take effect. Optional parameters:MOBILE,APP,WEB,ADMIN,API,OTHER, etc.
9. Custom terminal client
// 生成WEB令牌
$ user = [
' id ' => 2022 ,
' name ' => ' Tinywan ' ,
' client ' => JwtToken:: TOKEN_CLIENT_WEB
];
$ token = JwtToken:: generateToken ( $ user );
// 生成移动端令牌
$ user = [
' id ' => 2022 ,
' name ' => ' Tinywan ' ,
' client ' => JwtToken:: TOKEN_CLIENT_MOBILE
];
$ token = JwtToken:: generateToken ( $ user ); The default is WEB
10. Customize the expiration time of access token and refresh token
$ extend = [
' id ' => 2024 ,
' access_exp ' => 7200 , // 2 小时
];
$ token = Tinywan Jwt JwtToken:: generateToken ( $ extend );11. Token Expiration Error Code
401011401012401013401014401015401021401022401023401024401025 JWT's most common signature algorithms (JWA): HS256(HMAC-SHA256) , RS256(RSA-SHA256) and ES256(ECDSA-SHA256)
+--------------+-------------------------------+--------------------+
| " alg " Param | Digital Signature or MAC | Implementation |
| Value | Algorithm | Requirements |
+--------------+-------------------------------+--------------------+
| HS256 | HMAC using SHA - 256 | Required |
| HS384 | HMAC using SHA - 384 | Optional |
| HS512 | HMAC using SHA - 512 | Optional |
| RS256 | RSASSA - PKCS1 -v1_5 using | Recommended |
| | SHA - 256 | |
| RS384 | RSASSA - PKCS1 -v1_5 using | Optional |
| | SHA - 384 | |
| RS512 | RSASSA - PKCS1 -v1_5 using | Optional |
| | SHA - 512 | |
| ES256 | ECDSA using P- 256 and SHA - 256 | Recommended+ |
| ES384 | ECDSA using P- 384 and SHA - 384 | Optional |
| ES512 | ECDSA using P- 521 and SHA - 512 | Optional |
| PS256 | RSASSA - PSS using SHA - 256 and | Optional |
| | MGF1 with SHA - 256 | |
| PS384 | RSASSA - PSS using SHA - 384 and | Optional |
| | MGF1 with SHA - 384 | |
| PS512 | RSASSA - PSS using SHA - 512 and | Optional |
| | MGF1 with SHA - 512 | |
| none | No digital signature or MAC | Optional |
| | performed | |
+--------------+-------------------------------+--------------------+
The use of " + " in the Implementation Requirements column indicates
that the requirement strength is likely to be increased in a future
version of the specification.You can see that only RS256 and ES256 are marked Recommended.
The plug-in installation uses
HS256symmetric encryption algorithm by default.
HS256 uses the same 「secret_key」 for signature and verification. Once secret_key leaks, there is no security at all. Therefore, HS256 is only suitable for centralized authentication, and both signatures and verification must be carried out by trusted parties.
The RS256 series is signed using the RSA private key and verified using the RSA public key.
Even if the public key is leaked, it will have no effect. Just ensure the private key is secure. RS256 can delegate verification to other applications, just give them the public key.
The following are RS series algorithm generation commands for reference only
ssh-keygen -t rsa -b 4096 -E SHA512 -m PEM -P "" -f RS512 .key
openssl rsa -in RS512 .key -pubout -outform PEM -out RS512 .key.pubssh-keygen -t rsa -b 4096 -E SHA354 -m PEM -P "" -f RS384 .key
openssl rsa -in RS384 .key -pubout -outform PEM -out RS384 .key.pubssh-keygen -t rsa -b 4096 -E SHA256 -m PEM -P "" -f RS256 .key
openssl rsa -in RS256 .key -pubout -outform PEM -out RS256 .key.pubStudents who don’t understand can learn about the video, and there will be detailed instructions.
https://www.w3cschool.cn/fastapi/fastapi-cmia3lcw.html
There are many ways to deal with issues such as security, identity authentication, and authorization. And this is often a complex and “difficult” topic. In many frameworks and systems, dealing with security and identity authentication only takes a lot of effort and code (in many cases, it may account for 50% or more of all code written).
Jwt helps you handle security easily and quickly in a standard way without researching and learning all safety specifications.
Suppose you have a backend API in a domain. And you have a frontend in a different path (or mobile application) in another domain or the same domain. And you want there is a way to get the front-end to authenticate with the back-end using the username and password. We can use OAuth2 to build it through JWT.
username and password in the front end and clicks Enter.username and password to our API at a specific URL (to declare tokenUrl="token" ).Authorization a header with the value Bearer plus the token. If the token contains foobar , the content of the Authorization header will be: Bearer foobar .注意:中间是有个空格.