To send a JWT (JSON Web Token) to a mobile app using a PHP API, you typically follow these steps:
- Generate the JWT Token: Use a library to generate the JWT token on the server-side. PHP has several libraries available for this purpose, such as Firebase JWT (firebase/php-jwt) or lcobucci/jwt. You’ll need to encode the necessary claims into the token payload, such as user ID, expiration time, etc.
- Send the JWT Token in API Response: Once you generate the JWT token, include it in the response of your PHP API. You might structure your API response to include the token in a JSON object or as part of a response header.
- Handle the JWT Token in the Mobile App: In the mobile app, you’ll need to parse the response from the API to extract the JWT token. Once you have the token, you can store it securely on the device, typically in the device’s secure storage such as Keychain (iOS) or SharedPreferences (Android).
- Use the JWT Token for Subsequent Requests: In subsequent requests to your API, include the JWT token in the request headers as an authentication mechanism. Your PHP API should then verify the token’s authenticity and extract the necessary claims to identify the user and authorize the request.
Here’s a basic example in PHP demonstrating how you might generate and send a JWT token in an API response:
<?php
// Include the JWT library
require_once 'vendor/autoload.php';
use Firebase\JWT\JWT;
// Key for signing the token
$key = "your_secret_key";
// Claims for the token (example: user ID)
$claims = [
"user_id" => 123
];
// Token expiration time (example: 1 hour)
$expiration_time = time() + (60 * 60);
// Encode the token
$token = JWT::encode($claims, $key);
// Prepare the API response
$response = [
"token" => $token,
"expires_at" => $expiration_time
];
// Convert the response to JSON
$json_response = json_encode($response);
// Set response headers
header("Content-Type: application/json");
// Send the JSON response
echo $json_response;
?>
In this example, we’re using the Firebase JWT library to encode the token. Replace 'your_secret_key'
with your actual secret key for signing the token. Adjust the claims and expiration time as per your requirements.
On the mobile app side, you would parse the JSON response from the API to extract the token and store it securely. Then, you can include the token in subsequent API requests as an Authorization header.
Remember to handle errors, token expiration, and token validation securely in your implementation.