web-token/jwt-core
Core JWT component from the web-token JWT Framework. Provides foundational building blocks for JSON Web Tokens used by the framework. Read-only split package; development and issues belong in the main jwt-framework repository. Official docs available online.
## Technical Evaluation
### Architecture Fit
- **Stateless Auth Alignment**: Perfectly aligns with Laravel’s API-first architecture (e.g., Lumen, Sanctum, or Passport) by enabling JWT-based stateless authentication, eliminating session storage dependencies. However, it introduces complexity for traditional session-based Laravel applications.
- **Modular Design**: Acts as a low-level building block, requiring integration with Laravel’s existing auth stack (e.g., `Illuminate\Auth\Guard`, `Laravel\Sanctum`) rather than providing end-to-end solutions. This modularity is both a strength (flexibility) and weakness (boilerplate).
- **RFC 7519 Compliance**: Supports core JWT standards (HS256, RS256, ES256), ensuring interoperability with OAuth2/OpenID Connect workflows. However, lacks built-in support for advanced features like token revocation or key rotation.
- **Performance Considerations**: Lightweight core library with minimal overhead for symmetric algorithms (HS256), but asymmetric algorithms (RS256/ES256) may introduce latency due to cryptographic operations. Requires benchmarking against Laravel’s native `openssl` or `sodium` extensions.
### Integration Feasibility
- **Laravel Compatibility**: Fully compatible with Laravel 5.5+ (PHP 7.1+) and integrates seamlessly with Laravel’s dependency injection and service container. However, the lack of active maintenance introduces compatibility risks with newer PHP/Laravel versions (e.g., PHP 8.2+ features like enums or read-only properties).
- **Dependency Management**: No external dependencies beyond PHP’s core extensions (`openssl`, `json`), reducing bloat but requiring manual configuration of cryptographic keys and algorithms. Conflicts with other JWT libraries (e.g., `firebase/php-jwt`) due to overlapping functionality.
- **Key Features**:
- **Encoding/Decoding**: Supports JWT creation and validation with customizable algorithms.
- **Payload Handling**: Allows arbitrary claims (e.g., user roles, expiration times) but lacks built-in validation logic.
- **Algorithm Flexibility**: Supports HS256 (symmetric), RS256/ES256 (asymmetric), but requires manual key management.
- **Gaps**:
- No built-in token expiration handling (must be implemented manually in payload validation).
- No support for JWT compact serialization (requires pairing with `web-token/jwt-framework` or `base64url` utilities).
- No middleware or guard integrations (must be built custom).
### Technical Risk
- **Stagnation and Security**:
- Last release in **2017** poses risks:
- Vulnerabilities to modern cryptographic attacks (e.g., timing attacks, weak random number generation).
- Incompatibility with PHP 8.1+ features (e.g., constructor property promotion, union types).
- Lack of updates for new RFCs (e.g., RFC 9066 for BCP-159 token types).
- **Mitigation**: Pair with `spomky-labs/base64url` for serialization and monitor forks (e.g., `firebase/php-jwt`).
- **Cryptographic Risks**:
- No built-in protection against:
- Algorithm confusion attacks (requires strict validation of `alg` claim).
- Replay attacks (requires application-layer logic or external storage).
- Weak key management (no rotation or revocation mechanisms).
- **Mitigation**: Implement custom middleware to enforce security best practices.
- **Testing and Validation**:
- Manual validation required for edge cases (e.g., malformed tokens, algorithm mismatches, expired payloads).
- No built-in testing utilities (must integrate with Laravel’s testing tools like PEST or PHPUnit).
### Key Questions
1. **Algorithm Selection**:
- Is **HS256** sufficient for your use case, or do you need **RS256/ES256** for asymmetric key distribution? Asymmetric algorithms introduce higher computational overhead.
2. **Key Management**:
- How will cryptographic keys be stored, rotated, and secured? (e.g., Laravel’s `config`, AWS KMS, or Hashicorp Vault?)
3. **Token Lifecycle**:
- Will tokens be short-lived (JWTs as refresh tokens) or long-lived (requiring revocation)? Long-lived tokens need a blacklisting mechanism (e.g., Redis).
4. **Integration Strategy**:
- Will this replace Laravel’s existing auth (e.g., Sanctum/Passport) or augment it? Partial adoption may lead to inconsistency.
5. **Fallback Plan**:
- What is the backup if this package becomes unsustainable? Options include `firebase/php-jwt`, `league/oauth2-server`, or a custom implementation.
6. **Performance Requirements**:
- Can the system handle asymmetric crypto (RS256/ES256) at scale? Benchmark against Laravel’s native `openssl` functions.
7. **Compliance**:
- Does your use case require adherence to specific standards (e.g., FIPS 140-2 for government contracts)? This package may not meet such requirements.
---
## Integration Approach
### Stack Fit
- **Laravel Ecosystem**:
- **APIs**: Ideal for stateless authentication in Laravel APIs (Lumen, Sanctum, or Passport). Reduces session storage overhead and improves scalability.
- **Traditional Apps**: Poor fit unless migrating entirely from session-based auth to JWTs. Adds complexity without clear benefits for session-heavy applications.
- **Dependency Synergy**:
- Works alongside Laravel’s `Hash` facade for key derivation (e.g., `Hash::make()` for symmetric keys).
- Complements Laravel’s `Encrypter` for secure storage of sensitive payload data.
- Can integrate with Laravel’s caching layer (e.g., Redis) for key storage or revocation lists.
- **Conflict Risks**:
- Avoid mixing with other JWT libraries (e.g., `firebase/php-jwt`) to prevent versioning or API conflicts.
### Migration Path
1. **Assessment Phase**:
- Audit current authentication flows (e.g., Sanctum, Passport, or custom session auth).
- Identify gaps where JWTs would improve security, scalability, or compliance.
- Benchmark against alternatives like `firebase/php-jwt` or `league/oauth2-server`.
2. **Proof of Concept (PoC)**:
- Implement a **single endpoint** (e.g., `/api/auth/login`) to issue JWTs.
- Test with:
- Symmetric (HS256) and asymmetric (RS256) algorithms.
- Token expiration and payload validation.
- Integration with Laravel’s auth system (e.g., custom guard).
3. **Gradual Rollout**:
- Replace one auth provider at a time (e.g., API token guard for third-party clients).
- Use **feature flags** to toggle between old and new auth logic.
- Example: Route groups with `middleware('auth:jwt')` alongside existing middleware.
4. **Deprecation**:
- Phase out legacy session-based auth only after full JWT adoption.
- Sunset old endpoints in favor of JWT-protected routes.
### Compatibility
- **Laravel Versions**:
- Tested on Laravel 5.5–8.x (PHP 7.1–8.1). PHP 8.2+ may require polyfills for:
- Typed properties.
- Constructor property promotion.
- New attribute syntax.
- **Mitigation**: Use `composer require php:^8.1` with strict type checks.
- **Database**:
- No ORM hooks, but can store token metadata (e.g., `oauth_refresh_tokens` table for revocation).
- Example schema:
```sql
CREATE TABLE oauth_refresh_tokens (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
token VARCHAR(255) UNIQUE,
user_id BIGINT,
revoked_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
- **Caching**:
- Leverage Laravel’s cache (e.g., Redis) for:
- Storing public keys (for RS256/ES256).
- Blacklisting revoked tokens.
- Example:
```php
Cache::put('jwt_public_key', $publicKeyPem, now()->addHours(1));
```
### Sequencing
1. **Core Setup**:
- Install the package:
```bash
composer require web-token/jwt-core
```
- Configure keys in `config/services.php` or `.env`:
```env
JWT_SECRET=your-256-bit-secret
JWT_PUBLIC_KEY=-----BEGIN PUBLIC KEY-----
JWT_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----
```
- Create a JWT service provider:
```php
// app/Providers/JWTServiceProvider.php
public function register() {
$this->app->singleton('jwt', function () {
return new \WebToken\JWT\JWT();
});
}
```
2. **Middleware Creation**:
- Build a custom middleware to validate JWTs:
```php
// app/Http/Middleware/ValidateJWT.php
public function handle($request, Closure $next) {
$token = $request->bearerToken();
if (!$token) {
return response()->json(['error' => 'Unauthorized'], 4
How can I help you explore Laravel packages today?