Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Microsoft Jwt Laravel Package

alancting/php-microsoft-jwt

Laravel/PHP helper for validating Microsoft (Azure AD) JWTs. Fetches and caches JWKS signing keys, verifies token signatures and claims, and supports common AAD scenarios so APIs can authenticate Microsoft identity tokens with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require alancting/php-microsoft-jwt
    

    Add to composer.json under require if not using Composer globally.

  2. First Use Case: Validate a Microsoft JWT

    use Alancting\Microsoft\Jwt\Jwt;
    
    $jwt = new Jwt();
    $isValid = $jwt->validate('eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs...');
    
  3. Where to Look First

    • Source Code (if available, though repo is unknown).
    • Class Alancting\Microsoft\Jwt\Jwt for core functionality.
    • validate() method for basic validation.
    • decode() method for extracting claims without validation.

Implementation Patterns

Common Workflows

1. Validating and Decoding JWTs

$jwt = new Jwt();
$decoded = $jwt->decode('token_here', true); // true = validate
if ($decoded) {
    $claims = $decoded->getClaims();
    $issuer = $claims['iss']; // e.g., "https://login.microsoftonline.com/"
}

2. Integrating with Laravel Middleware

use Alancting\Microsoft\Jwt\Jwt;

class MicrosoftAuthMiddleware
{
    public function handle($request, Closure $next)
    {
        $jwt = new Jwt();
        if (!$jwt->validate($request->bearerToken())) {
            abort(401, 'Invalid Microsoft JWT');
        }
        return $next($request);
    }
}

3. Extracting Specific Claims

$decoded = $jwt->decode('token_here');
$userId = $decoded->getClaim('oid'); // Microsoft's user ID claim
$tenantId = $decoded->getClaim('tid'); // Tenant ID

4. Handling Exceptions

try {
    $jwt->validate('invalid_token');
} catch (\Alancting\Microsoft\Jwt\Exception\InvalidToken $e) {
    // Handle invalid token
}

Integration Tips

Laravel Auth Integration

  • Use validate() in a custom guard or middleware.
  • Store decoded claims (e.g., oid, tid) in the user session or database.

Caching Decoded Tokens

$cacheKey = 'microsoft_jwt_' . md5($token);
$decoded = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($jwt, $token) {
    return $jwt->decode($token);
});

Logging JWT Claims

$decoded = $jwt->decode($token);
\Log::debug('Microsoft JWT Claims', $decoded->getClaims());

Gotchas and Tips

Pitfalls

1. Token Expiration

  • Always check exp (expiration) claim manually if not using validate():
    $exp = $decoded->getClaim('exp');
    if ($exp < time()) {
        throw new \RuntimeException('Token expired');
    }
    

2. Missing Claims

  • Microsoft tokens may omit optional claims (e.g., name). Handle missing keys gracefully:
    $name = $decoded->getClaim('name', 'Anonymous');
    

3. Algorithm Validation

  • The package defaults to RS256. If using other algorithms (e.g., HS256), configure explicitly:
    $jwt = new Jwt(['algorithm' => 'HS256']);
    

4. Clock Skew

  • Microsoft tokens may have slight time skew. Adjust leeway in validation:
    $jwt->setLeeway(60); // 60 seconds
    

Debugging Tips

1. Inspect Raw Token

$decoded = $jwt->decode('token_here', false); // Skip validation
\Log::debug('Raw Claims', $decoded->getClaims());

2. Verify Issuer (iss)

  • Ensure the iss claim matches Microsoft’s expected value:
    $issuer = $decoded->getClaim('iss');
    if (!str_starts_with($issuer, 'https://login.microsoftonline.com/')) {
        throw new \RuntimeException('Invalid issuer');
    }
    

3. Check Audience (aud)

  • Validate the aud claim matches your app’s client ID:
    $aud = $decoded->getClaim('aud');
    if ($aud !== config('services.microsoft.client_id')) {
        throw new \RuntimeException('Invalid audience');
    }
    

Extension Points

1. Custom Claim Validation

$jwt->setCustomValidator(function ($claims) {
    if ($claims['iss'] !== 'https://login.microsoftonline.com/your-tenant') {
        return false;
    }
    return true;
});

2. Override Default Config

$jwt = new Jwt([
    'algorithm' => 'RS256',
    'leeway' => 30,
    'issuer' => 'https://login.microsoftonline.com/'
]);

3. Extend for Azure AD Specifics

  • Add helper methods for Azure AD claims (e.g., getUserPrincipalName()):
    $upn = $decoded->getClaim('preferred_username');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky