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


// Create a new auth provider instance
$authProvider = new App\Providers\AuthProvider();

// Create a new jwt provider instance
$jwtProvider = new App\Providers\JwtProvider();

// Build up jwt claims
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory::build([
    'exp' => 1582243200, // Friday, 21 February 2020 00:00:00
    'iat' => 1582193571, // Thursday, 20 February 2020 10:12:51
    'iss' => 'https://example.com',
    'jti' => 'fVcx9BJHqh',
    'nbj' => '1582193571', // Thursday, 20 February 2020 10:12:51
]);

// Bring everything together to create a jwt auth instance
$jwtAuth = new JwtAuth($authProvider, $jwtProvider, $claimsFactory);

namespace App\Providers;

use Anddye\JwtAuth\Providers\AuthProviderInterface;

class AuthProvider implements AuthProviderInterface
{
    public function byCredentials(string $username, string $password)
    {
        // TODO: Validate username / password and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject`
    }

    public function byId(int $id)
    {
        // TODO: Find a user by id and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject` if exists
    }
}

namespace Anddye\JwtAuth\Tests\Stubs\Providers;

use Anddye\JwtAuth\Providers\JwtProviderInterface;

class JwtProvider implements JwtProviderInterface
{
    public function decode(string $token)
    {
        // TODO: Decode JWT token somehow
    }

    public function encode(array $claims): string
    {
        // TODO: Encode claims and create a JWT token somehow
    }
}

$claimsFactory = new Anddye\JwtAuth\ClaimsFactory();
$claimsFactory->setExp(1582243200); // Friday, 21 February 2020 00:00:00
$claimsFactory->setIat(1582193571); // Thursday, 20 February 2020 10:12:51
$claimsFactory->setIss('https://example.com');
$claimsFactory->setJti('fVcx9BJHqh');
$claimsFactory->setNbj(1582193571); // Thursday, 20 February 2020 10:12:51

if (!$token = $jwtAuth->attempt($username, $password)) {
    // TODO: Handle failed attempt with credentials
} else {
    // TODO: Handle successful attempt with credentials
}

if (!$actor = $jwtAuth->authenticate($token)->getActor()) {
    // TODO: Handle failed authentication with token
} else {
    // TODO: Handle successful authentication with token
}