PHP code example of abublihi / laravel-external-jwt-guard

1. Go to this page and download the library: Download abublihi/laravel-external-jwt-guard 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/ */

    

abublihi / laravel-external-jwt-guard example snippets





return [
    'authorization_servers' => [
        'default' => [
            /* Identification settings */
            'id_claim' => env('JWT_GUARD_ID_CLAIM', 'sub'),
            'roles_claim' => env('JWT_GUARD_ROLES_CLAIM', 'roles'),
            'id_attribute' => env('JWT_GUARD_ID_ATTRIBUTE', 'id'),

            /* Creation setting */
            'create_user' =>  env('JWT_GUARD_CREATE_USER', false),
            'create_user_action_class' => null,
            
            /* Validation settings */
            'issuer' => '',
            'validate_issuer' => true,
            'public_key' => env('JWT_GUARD_AUTH_SERVER_PUBLIC_KEY'), // if RSA, make sure it's start with -----BEGIN PUBLIC KEY----- and ends with -----END PUBLIC KEY-----
            'signing_algorithm' => env('JWT_GUARD_AUTH_SIGN_ALG', 'RS256'),
        ],
        // you could add as many as you want of the authorization servers by duplicating the configurations above ^^
        'admin' => [ 'id_claim' => 'sub', ..... ]
    ],
];


'id_claim' => env('JWT_GUARD_ID_CLAIM', 'sub'),
'roles_claim' => env('JWT_GUARD_ROLES_CLAIM', 'roles'), // not yet used
'id_attribute' => env('JWT_GUARD_ID_ATTRIBUTE', 'id'), // in your database (e.g. users table)

'create_user' =>  env('JWT_GUARD_CREATE_USER', false),
// you can define your own action by implementing the interface Abublihi\LaravelExternalJwtGuard\Interfaces\CreateUserActionInterface
'create_user_action_class' => null,

'issuer' => 'https://example.com',
'validate_issuer' => true,
'public_key' => env('JWT_GUARD_AUTH_SERVER_PUBLIC_KEY'), // if RSA, make sure it's start with -----BEGIN PUBLIC KEY----- and ends with -----END PUBLIC KEY-----
'signing_algorithm' => env('JWT_GUARD_AUTH_SIGN_ALG', 'RS256'),

'guards' => [
    .
    .
    'api-jwt' => [
        'driver' => 'external-jwt-auth', // <-- here you have to set the drive to `external-jwt-auth`
        'provider' => 'users',
    ],
    
    // you can set the authorization server key as seen below 
    'api-jwt-admin' => [
        'driver' => 'external-jwt-auth', // <-- here you have to set the drive to `external-jwt-auth`
        'provider' => 'users',
        'auth_server_key' => 'admin', // the authorization key for admin 
    ],
    .
    .
],

Route::middleware('auth:api-jwt')->group(function() {
    Route::get('user', function(){
        return request()->user(); // <-- will return the user which is configured
    });
});

protected $middlewareAliases = [
    // ...
    'jwt-role' => \Abublihi\LaravelExternalJwtGuard\Middleware\CheckJwtRoles::class
];

Route::group(['middleware' => ['auth:api-jwt' 'jwt-role:manager']], function () {
    // this will allow any jwt with the role `manager`
});

Route::group(['middleware' => ['auth:api-jwt' 'jwt-role:manager|super-admin']], function () {
    // this will allow any jwt with the role `manager` or `super-admin`
});

use Abublihi\LaravelExternalJwtGuard\Middleware\CheckJwtRoles;

Route::group(['middleware' => ['auth:api-jwt' CheckJwtRoles::class.':manager']], function () {
    // this will allow any jwt with the role `manager`
});

// with OR operator 
Route::group(['middleware' => ['auth:api-jwt' CheckJwtRoles::class.':manager|super-admin']], function () {
    // this will allow any jwt with the role `manager`
});

class SampleTest extends TestCase
{
    use DatabaseMigrations, \Abublihi\LaravelExternalJwtGuard\Traits\ActingAs;

    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_authenticated_user_by_jwt()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt($user);
    }
}

use Abublihi\LaravelExternalJwtGuard\Support\FakeTokenIssuer;

class SampleTest extends TestCase
{
    use DatabaseMigrations, \Abublihi\LaravelExternalJwtGuard\Traits\ActingAs;

    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_authenticated_when_with_role_admin()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt(
            FakeTokenIssuer:user($user)
                ->withClaims([
                    'roles' => [
                        'admin'
                    ]
                ])
        );
    }

    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_authenticated_when_with_custom_claim_employee_name()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt(
            FakeTokenIssuer:user($user)
                ->withClaims([
                    'employee_name' => 'Mohammed Abdullah',
                    'other_info' => [
                        'info 1',
                        'info 2'
                    ]
                ])
        );
    }

    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_unauthenticated_when_invaild()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt(
            FakeTokenIssuer:user($user)
                ->asInvalid()
        );
    }
 
    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_unauthenticated_when_expired()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt(
            FakeTokenIssuer:user($user)
                ->asExpired()
        );
    }
}

class SampleTest extends TestCase
{
    use DatabaseMigrations, \Abublihi\LaravelExternalJwtGuard\Traits\ActingAs;

    /**
     * @test
     * @define-route usesAuthRoutes
     */
    function test_it_returns_authenticated_user_by_jwt()
    {
        $user = User::factory()->create();

        $this->actingAsExternalJwt($user, 'admin'); // this will set the authorization server key to `admin`
    }
}
bash
php artisan vendor:publish --provider="Abublihi\LaravelExternalJwtGuard\LaravelExternalJwtGuardServiceProvider" --tag config