Home  >  Article  >  Backend Development  >  How to use JWT for API authentication in PHP

How to use JWT for API authentication in PHP

PHPz
PHPzOriginal
2023-06-17 22:04:281130browse

With the development of web applications, API authentication has become an integral part of modern web applications. JSON Web Token (JWT) is an open standard for authentication and authorization that provides a secure and reliable way to authenticate users and implement single sign-on. This article will explain how to use JWT for API authentication in PHP.

What is JWT?

JSON Web Token (JWT) is a standard based on the JSON format, which can be used to securely transmit information over the Internet. JWT usually consists of three parts: header, payload and signature.

  • Header: Contains the algorithm used by JWT, such as HMAC SHA256 or RSA.
  • Payload: Contains data about users, permissions, or other related information.
  • Signature: used to verify the authenticity and integrity of the Token.

JWT workflow

When the user logs in, the server will assign a JWT to the user. This JWT will be sent to the client and saved in the client's cookie or local storage. When a user wants to access a protected API, the client sends a JWT back to the server. The server will check the JWT's signature and verify the data in the payload to ensure the user has permission to access the API. If the JWT passes validation, the server authorizes the user to access the API.

Using PHP to implement JWT authentication

In PHP, we can use some popular open source libraries to implement JWT authentication. This article will use Firebase's JWT library, which provides a simple API to create and verify JWTs. Here is a simple example:

  1. Install Firebase JWT library:

composer require firebase/php-jwt

  1. Create JWT:

The following code will create a JWT that contains a signature and custom payload data.

use FirebaseJWTJWT;

// Set the payload data (custom data)
$payload = [
    "user_id" => 1,
    "username" => "john.doe",
];
 
// Generate JWT using secret key
$jwt = JWT::encode($payload, 'secret_key');
  1. Verify JWT:

The code below will verify the signature of the JWT and check if the payload data is valid.

use FirebaseJWTJWT;

// Verify JWT using secret key
try {
    $decoded = JWT::decode($jwt, 'secret_key', array('HS256'));
} catch (Exception $e) {
    // Handle invalid JWT
}
 
// Access the payload data
$user_id = $decoded->user_id;
$username = $decoded->username;
  1. Send JWT to client:

After creating the JWT, we can send it to the client and store it in a cookie or local storage.

// Set JWT as a cookie
setcookie('token', $jwt, time()+3600, '/');
  1. Verify the JWT sent by the client:

We can use similar code as the server side to verify the JWT sent by the client.

use FirebaseJWTJWT;

// Get JWT from cookie or local storage
$jwt = $_COOKIE['token'];
 
// Verify JWT using secret key
try {
    $decoded = JWT::decode($jwt, 'secret_key', array('HS256'));
} catch (Exception $e) {
    // Handle invalid JWT
}
 
// Access the payload data
$user_id = $decoded->user_id;
$username = $decoded->username;

Summary

JWT is a secure and reliable authentication mechanism suitable for modern web applications. JWT authentication can be easily implemented using PHP and Firebase JWT library. When implementing API authentication, make sure to only store JWTs in a secure place and use HTTPS for protected transmission.

The above is the detailed content of How to use JWT for API authentication in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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