How to use PHP for JWT authentication and authentication?
JWT (JSON Web Token) is an open standard for authentication and authorization. It transfers data between the client and server in a safe and reliable manner and allows the server to verify the identity of the user sending the request. This article will introduce how to use PHP to implement JWT authentication and authentication functions.
composer require firebase/php-jwt lcobucci/jwt
<?php use FirebaseJWTJWT; use LcobucciJWTBuilder; use LcobucciJWTSignerHmacSha256; // 用户登录成功后,生成JWT function generateJWT($userId, $secretKey) { $time = time(); $token = (new Builder()) ->issuedBy('example.com') // 发行者 ->permittedFor('example.com') // 接受者 ->identifiedBy('1', true) // 标识符 ->issuedAt($time) // 发行时间 ->expiresAt($time + 3600) // 过期时间 ->withClaim('userId', $userId) // 自定义声明 ->getToken(new Sha256(), new Key($secretKey)); return $token; } $jwt = generateJWT(1, 'your-secret-key'); echo $jwt;
<?php use FirebaseJWTJWT; // 验证并解析JWT function verifyJWT($jwt, $secretKey) { try { $decoded = JWT::decode($jwt, $secretKey, ['HS256']); return $decoded; } catch (Exception $e) { return null; } } $jwt = $_SERVER['HTTP_AUTHORIZATION']; $decoded = verifyJWT($jwt, 'your-secret-key'); if ($decoded) { $userId = $decoded->userId; echo "用户ID:$userId"; } else { echo "无效的JWT"; }
<?php use FirebaseJWTJWT; use LcobucciJWTBuilder; use LcobucciJWTSignerHmacSha256; // 刷新JWT function refreshJWT($jwt, $secretKey) { $current = time(); $decoded = JWT::decode($jwt, $secretKey, ['HS256']); if ($decoded->exp - $current > 1800) { // 如果剩余有效期超过30分钟,则不刷新JWT return $jwt; } $newToken = (new Builder()) ->issuedBy($decoded->iss) ->permittedFor($decoded->aud) ->identifiedBy($decoded->jti, true) ->issuedAt($current) ->expiresAt($current + 3600) ->withClaim('userId', $decoded->userId) ->getToken(new Sha256(), new Key($secretKey)); return $newToken; } $jwt = $_SERVER['HTTP_AUTHORIZATION']; $refreshedJWT = refreshJWT($jwt, 'your-secret-key'); echo $refreshedJWT;
Through the above steps, we can easily implement JWT authentication and authentication functions using PHP. Of course, practical applications require more security considerations and practices, and adjustments based on specific needs. I hope this article will help you understand and use JWT!
The above is the detailed content of How to use PHP for JWT authentication and authentication?. For more information, please follow other related articles on the PHP Chinese website!