Mastering JWT Authentication in PHP: From Basics to Advanced Usage
This guide explains the limitations of traditional session authentication, introduces JSON Web Token (JWT) as a scalable cross‑domain solution, and provides step‑by‑step instructions for installing, configuring, generating, and validating JWTs in PHP applications, including supported algorithms and practical code examples.
Why Traditional Session Authentication Fails at Scale
Typical web authentication stores user information in a server‑side session and passes a session_id via cookies. This works for a single server but does not scale across multiple servers or domains because every instance must share the session store, creating a heavy engineering burden and a single point of failure.
JWT: A Stateless Alternative
JSON Web Token (JWT) moves all authentication data to the client. After verifying credentials, the server issues a signed token. The client includes the token in the Authorization: Bearer <token> header for every subsequent API request. Tokens carry an expiration time, limiting the impact of a stolen token.
Authentication Flow
User enters username and password in the frontend.
The frontend sends the credentials to the token endpoint (e.g., /token).
The API validates the credentials and returns a signed JWT.
The frontend stores the token temporarily (e.g., in memory or secure storage).
For protected resources, the frontend adds Authorization: Bearer <token> to each request.
Installing the JWT Plugin (PHP)
composer require tinywan/jwtGenerating a Token
$user = [
'id' => 2022, // unique global identifier
'name' => 'Tinywan',
'email' => '[email protected]'
];
$token = Tinywan\Jwt\JwtToken::generateToken($user);
var_dump(json_encode($token));The JSON response includes:
token_type : "Bearer" – token scheme.
expires_in : token lifetime in seconds (e.g., 36000).
access_token : the JWT string used for authentication.
refresh_token : a token that can be exchanged for a new access token after expiration.
Supported JWT Methods
getCurrentId()– retrieve the current user ID. getExtend() – obtain all custom claims. getExtendVal('email') – fetch a specific claim. refreshToken() – exchange a refresh token for a new access token. getTokenExp() – get remaining token lifetime (seconds).
Single‑device login (enable by setting 'is_single_device' => true in config/plugin/tinywan/jwt). getUser() – retrieve the current user model (requires plugin version >= 1.2.4). clear() – remove expired tokens.
Configuring User Model Retrieval
Define a 'user_model' anonymous function that receives the user ID and returns the corresponding user record. This allows the plugin to work with any ORM.
'user_model' => function($uid) {
return \think\facade\Db::table('resty_user')
->field('id,username,create_time')
->where('id', $uid)
->find();
}, 'user_model' => function($uid) {
return \support\Db::table('resty_user')
->where('id', $uid)
->select('id','email','mobile','create_time')
->first();
},Signature Algorithms Supported by the Plugin
HS256 (HMAC‑SHA256) – symmetric, default.
RS256 (RSA‑SHA256) – asymmetric, recommended.
ES256 (ECDSA‑SHA256) – asymmetric, recommended.
Symmetric vs Asymmetric Encryption
HS256 signs and verifies tokens with a shared secret_key. If the secret leaks, any party can forge valid tokens, so HS256 is suitable only for closed, centralized environments.
RS256 signs tokens with a private RSA key and verifies them with the corresponding public key. The public key can be distributed freely, while the private key must remain confidential, enabling secure verification across multiple services.
Generating RSA Keys (Example Commands)
# RS256 (4096‑bit RSA, SHA‑256)
ssh-keygen -t rsa -b 4096 -E SHA256 -m PEM -P "" -f RS256.key
openssl rsa -in RS256.key -pubout -outform PEM -out RS256.key.pub
# RS384 (4096‑bit RSA, SHA‑384)
ssh-keygen -t rsa -b 4096 -E SHA384 -m PEM -P "" -f RS384.key
openssl rsa -in RS384.key -pubout -outform PEM -out RS384.key.pub
# RS512 (4096‑bit RSA, SHA‑512)
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.pubAlgorithm selection and related options are configured in config/plugin/tinywan/jwt/app.php.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
