Sobes.tech
Junior — Middle

Kas saaksite jagada oma kogemust JSON Web Tokensi kasutamisel projektides?

sobes.tech AI

Vastus AI-lt

In PHP projects, I have used JSON Web Tokens (JWT) to implement user authentication and authorization. JWT allows transmitting user information in an encrypted form between the client and server without the need to store sessions on the server.

Main steps for using JWT:

  1. After successful authentication, the user receives a JWT containing the payload (e.g., user ID, roles).
  2. The token is signed with a secret key to prevent forgery.
  3. The client stores the token (e.g., in localStorage) and sends it in the Authorization header in subsequent requests.
  4. The server verifies the token's signature and extracts data to determine access rights.

Example of creating a JWT using the firebase/php-jwt library:

use Firebase\JWT\JWT;

$payload = [
    'iss' => 'your-domain.com',
    'iat' => time(),
    'exp' => time() + 3600, // validity period of 1 hour
    'userId' => 123
];

$jwt = JWT::encode($payload, $secretKey, 'HS256');

// For verification:
$decoded = JWT::decode($jwt, $secretKey, ['HS256']);

Using JWT simplifies scaling applications, as it does not require storing sessions on the server, but it is important to properly set the token's expiration time and manage its renewal.