How does a server manage and verify JWT tokens, especially in the context of API authentication?
To manage and verify JWT tokens in the context of API authentication, a server needs to validate the token's signature using a secret key, check the token's expiration date, and ensure that the token is issued by a trusted source. This process helps to authenticate users and authorize access to protected resources securely.
<?php
use Firebase\JWT\JWT;
// JWT token verification
$jwt = $_SERVER['HTTP_AUTHORIZATION'];
$secret_key = "your_secret_key";
try {
$decoded = JWT::decode($jwt, $secret_key, array('HS256'));
// Token is valid, proceed with API request
// Access user information from $decoded object
} catch (Exception $e) {
// Token is invalid or expired
http_response_code(401);
echo json_encode(array("message" => "Unauthorized"));
}