PHP code example of andrewdyer / jwt-auth

1. Go to this page and download the library: Download andrewdyer/jwt-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andrewdyer / jwt-auth example snippets


namespace App\Models;

use Anddye\JWTAuth\Interfaces\JWTSubject;

class User implements JWTSubject
{
    public function getJWTIdentifier(): int
    {
        return 1;
    }
}

namespace App\Providers;

use Anddye\JWTAuth\Interfaces\AuthProviderInterface;
use App\Models\User;

class AuthProvider implements AuthProviderInterface
{
    public function byCredentials(string $username, string $password)
    {
        if ($username === 'admin' && $password === 'secret') {
            return new User();
        }

        return null;
    }

    public function byId(int $id)
    {
        if ($id === 1) {
            return new User();
        }

        return null;
    }
}

namespace App\Providers;

use Anddye\JWTAuth\Interfaces\JWTProviderInterface;

class JWTProvider implements JWTProviderInterface
{
    public function decode(string $token)
    {
        return json_decode(base64_decode($token), true);
    }

    public function encode(array $claims): string
    {
        return base64_encode(json_encode($claims));
    }
}

use Anddye\JWTAuth\Factory\ClaimsFactory;

$claims = ClaimsFactory::build([
    'iss' => 'https://example.com',     // Issuer of the JWT
    'aud' => 'https://example.com',     // Audience of the JWT
    'exp' => 1582243200,                // Expiration time (Unix timestamp)
    'nbf' => 1582193571,                // Not before time (Unix timestamp)
    'iat' => 1582193571,                // Issued at time (Unix timestamp)
    'jti' => 'fVcx9BJHqh',              // Unique identifier
]);

use App\Providers\AuthProvider;
use App\Providers\JWTProvider;
use Anddye\JWTAuth\JWTAuth;

$authProvider = new AuthProvider();

$jwtProvider = new JWTProvider();

$jwtAuth = new JWTAuth($authProvider, $jwtProvider, $claims);

try {
    $token = $jwtAuth->attempt('admin', 'secret');
    echo "Token: " . $token;
} catch (\Anddye\JWTAuth\Exceptions\InvalidCredentialsException $e) {
    echo "Invalid credentials";
}

$subject = $jwtAuth->authenticate('your-jwt-token-here');

if ($subject) {
    echo "User authenticated!";
} else {
    echo "Invalid token";
}