ronasit/laravel-clerk

Package provides auth guard to auth user via the Clerk

Maintainers

Package info

github.com/RonasIT/laravel-clerk

pkg:composer/ronasit/laravel-clerk

Statistics

Installs: 9 030

Dependents: 0

Suggesters: 0

Stars: 9

Open Issues: 6


README

Coverage Status

Laravel Clerk Guard

Introduction

This package offers an authentication guard to seamlessly integrate Clerk authentication into your Laravel project.

Installation

  1. Use Composer to install the package:
composer require ronasit/laravel-clerk
  1. Run package's install command
php artisan laravel-clerk:install
  1. Populate the necessary configuration options in config/clerk.php.

Usage

By default, your app returns the User class with just the external_id property, which holds the user's ID in Clerk.

To customize this behavior, you'll need to create your own UserRepository that implements the UserRepositoryContract. Then, rebind it in one of the service providers:

use RonasIT\Clerk\Contracts\UserRepositoryContract;
use App\Support\Clerk\MyAwesomeUserRepository;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->app->bind(UserRepositoryContract::class, MyAwesomeUserRepository::class);
    }
}

Testing

To test authenticated user requests guarded by ClerkGuard, use the TokenMockTrait:

  1. Ensure clerk config is completely filled using .env.testing file or dynamically:
Config::set('clerk', [
    'allowed_issuer' => 'issuer',
    'secret_key' => 'my_secret_key',
    'signer_key_path' => 'path/to/my/signer-key',
]);
  1. Generate a JWT token and pass it to the Authorization header:
use RonasIT\Clerk\Traits\TokenMockTrait;

class UserRepositoryTest extends TestCase
{
    use TokenMockTrait;
    
    public function test()
    {
        $clerkToken = $this
            ->createJWTToken(
                relatedTo: 'user_id',
                issuer: 'issuer',
            )
            ->toString();
            
        $this->withHeader('Authorization', "Bearer {$clerkToken}");     
    }
}
  1. You may also pass custom claims to the token using claims parameter:
    $clerkToken = $this
        ->createJWTToken(
            relatedTo: 'user_id',
            issuer: 'issuer',
            claims: [
                'email' => 'user@mail.com',
                'phone' => '+1234567789',
            ],
        )->toString();