Home > Backend Development > PHP Tutorial > How to use PHP for JWT authentication and authentication?

How to use PHP for JWT authentication and authentication?

WBOY
Release: 2023-08-07 10:14:01
Original
1387 people have browsed it

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.

  1. Installing dependent libraries
    JWT depends on two libraries: Firebase PHP JWT and lcobucci/jwt. You can use Composer to install these two libraries:
composer require firebase/php-jwt lcobucci/jwt
Copy after login
  1. Generate JWT
    First, we need to generate a JWT after the user successfully logs in and send it to the client. The following is a sample code:
<?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;
Copy after login
  1. Verify JWT
    After the server receives the client's request, we need to verify the legitimacy of the JWT and obtain the user's identity information. Here is a sample code:
<?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";
}
Copy after login
  1. Refresh JWT
    JWT expires after some time, but we can use refresh token to extend the validity period. The following is a sample code:
<?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;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template