devraeph/laravel-xtoken

This Package creates a JWTToken for the Application and provides a middelware for Auth

1.5.4 2022-08-22 19:13 UTC

This package is auto-updated.

Last update: 2024-10-22 23:40:26 UTC


README

Social Card of laravel-xtoken

DevRaeph / laravel-xtoken

Total Downloads Latest Stable Version Issues

A simple package with which you can issue JWT tokens and also verify them. Usable for multiple models, thanks to existing trait.

Installation

Package is available on Packagist, you can install it using Composer.

composer require devraeph/laravel-xtoken

Migrate Database for token table

php artisan migrate

Publish Config

php artisan vendor:publish --provider="DevRaeph\XToken\JWTTokenServiceProvider" --tag="config"

Documentation

Model-Trait HasXToken
Example:

namespace App\Models;
use DevRaeph\XToken\Traits\HasXToken;

class User extends Authenticatable
{
    use HasFactory, HasXToken;

    ...
}

Issuing a Token:

use DevRaeph\XToken\Facades\Tokenizer;
use Carbon\CarbonImmutable;

$myJWT = Tokenizer::setModel(/* MODEL eg USER */)
        ->setIssuedBy(/* Default is env("APP_URL") */)
        ->setExpiresAt(CarbonImmutable::now()->addDays(15))
        ->createToken();      
        
return $myJWT->toArray(); //Return Token Array
return $myJWT->toJson();  //Return Token Json

Using Middelware in Routes to parse Token:

/*
 * Use exsisting `xToken` middleware
 */
Route::group(['middleware' => ['api','xToken']], function () {
    Route::post("verify",function (){
        echo "Checked Token -> Valid";
    });
});

Get TokenClaim -> ID of Model

use App\Models\User;
use DevRaeph\XToken\Facades\TokenizerClaim;

$myClaim = TokenizerClaim::setRequest($request)
    ->get();
    
$myUser = User::whereId($myClaim)->first();