hyrioo/hyrnatic-authenticator

This is my package hyrnatic-authenticator

dev-main 2024-03-14 19:28 UTC

This package is not auto-updated.

Last update: 2024-04-25 19:55:59 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

JWT based authentication for Laravel
With refresh tokens and automatic reuse detection.

Installation

You can install the package via composer:

composer require hyrioo/hyrnatic-authenticator
php artisan vendor:publish --provider="Hyrioo\HyrnaticAuthenticator\HyrnaticAuthenticatorServiceProvider"

You can publish and run the migrations with:

php artisan vendor:publish --tag="hyrnatic-authenticator-migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --tag="hyrnatic-authenticator-config"

Usage

Update user model

Add the Hyrioo\HyrnaticAuthenticator\HasApiTokens trait to your user model.

use Hyrioo\HyrnaticAuthenticator\Traits\HasApiTokens;
 
class User extends Authenticatable
{
    use HasApiTokens;
}

Configure auth guard

Add hyrnatic-authenticator as the driver to your api guard.
Example:

'guards' => [
        'api' => [
            'driver' => 'hyrnatic-authenticator',
            'provider' => 'users',
        ],
    ],

Issuing tokens

When issuing a new token, you will get a new token family, an access token and a refresh token. The token family can have a name, if you eg. want to show the active logins for the user. You can set individual expire for all three. It's also possible to set custom claims for both the access and refresh token.

$builder = auth('api')->create($user) // NewTokenBuilder
$builder->setName('Phone'); // Optional
$builder->setScopes(['photo.manage']); // Optional
$builder->setFamilyExpiresAt(now()->addYear()); // Optional
$builder->setAccessExpiresAt(now()->addMinutes(5)); // Optional
$builder->setRefreshExpiresAt(now()->addMonth()); // Optional

$token = $builder->getToken();
$token->accessToken;
$token->refreshToken;

Refresh token

When refreshing the token, you can set a new expiry for both the access and refresh tokens. But scopes and custom claims will be the same.

$builder = auth('api')->refresh($request->refresh_token); // RefreshTokenBuilder
$builder->setAccessExpiresAt(now()->addMinutes(5)); // Optional
$builder->setRefreshExpiresAt(now()->addMonth()); // Optional

$token = $builder->refreshToken();
$token->accessToken;
$token->refreshToken;

Revoke token

When revoking a token the entire token family will be revoked, and both refresh and access tokens will stop working.

auth('api')->logout();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.