Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement JWT authentication for PUT/PATCH/DELETE requests #262

Open
JohnRDOrazio opened this issue Nov 17, 2024 · 0 comments
Open

implement JWT authentication for PUT/PATCH/DELETE requests #262

JohnRDOrazio opened this issue Nov 17, 2024 · 0 comments
Milestone

Comments

@JohnRDOrazio
Copy link
Member

Currently the API is still in a primitive state when it comes to authentication. No authentication mechanisms are implemented. We should implement JWT for PUT/PATCH/DELETE requests.

It should possible to implement JSON Web Token (JWT) authentication in a PHP API without using a database.

Key Concepts

  1. JWT Structure:

    • A JWT consists of three parts: Header, Payload, and Signature.
    • The Payload contains user data and claims.
    • The Signature is used to verify the authenticity of the token.
  2. Database-Free Approach:

    • User credentials or session data can be stored elsewhere, such as in a configuration file, environment variables, or in-memory cache (e.g., Redis).
    • Authentication and authorization decisions are made based on the JWT's payload.

Steps to Implement

1. Install a JWT Library

Use a PHP JWT library like firebase/php-jwt:

composer require firebase/php-jwt

2. Generate a JWT

You can generate a JWT when a user logs in with their credentials.

<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$key = 'your-secret-key'; // Use a strong secret key
$payload = [
    'iss' => 'your-api',  // Issuer
    'aud' => 'your-client',  // Audience
    'iat' => time(),       // Issued at
    'exp' => time() + 3600, // Expiration time (1 hour)
    'user_id' => 123       // User-specific data
];

$jwt = JWT::encode($payload, $key, 'HS256');
echo $jwt;
?>

3. Verify the JWT

When a client makes a request with a JWT, you verify its authenticity:

<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$key = 'your-secret-key'; // Must match the key used to generate the JWT

$jwt = $_SERVER['HTTP_AUTHORIZATION']; // Typically sent in the Authorization header
try {
    $decoded = JWT::decode($jwt, new Key($key, 'HS256'));
    print_r($decoded);
    // Proceed with the request, as the token is valid
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized: ' . $e->getMessage()]);
}
?>

4. Stateless Authentication

  • Once the JWT is issued, the server does not need to keep any session or token-related data.
  • Each request includes the JWT, and the server verifies it.

Considerations

  1. Secret Key Security:

    • Store your secret key securely using environment variables or a secure configuration system.
  2. Token Expiry:

    • Ensure tokens have a reasonable expiration time to reduce the risk of misuse.
  3. Token Revocation (optional):

    • Without a database, revoking tokens is challenging. You can introduce a blacklist mechanism in a cache like Redis or rely on short-lived tokens.
  4. HTTPS:

    • Always use HTTPS to protect the token during transmission on a production instance. Not required for a localhost instance.

This method ensures secure, stateless authentication without requiring a database.

@JohnRDOrazio JohnRDOrazio added this to the v5.0 milestone Jan 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant