1. Go to this page and download the library: Download a2workspace/laravel-jwt 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/ */
a2workspace / laravel-jwt example snippets
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use A2Workspace\LaravelJwt\HasApiTokens;
use A2Workspace\LaravelJwt\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
}
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use A2Workspace\LaravelJwt\LaravelJwt;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
if (! $this->app->routesAreCached()) {
LaravelJwt::routes();
}
}
}
// routes/api.php
Route::middleware('auth:api')->get('/auth/user', function (Request $request) {
return new UserResource($request->user());
});
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use A2Workspace\LaravelJwt\AuthenticatesUsers;
class AuthController extends Controller
{
use AuthenticatesUsers;
/**
* 回傳認證守衛
*
* @return \PHPOpenSourceSaver\JWTAuth\JWTGuard
*/
protected function guard(): JWTGuard
{
return Auth::guard('admin');
}
/**
* 取得驗證使用者名稱的欄位
*
* @return string
*/
protected function username()
{
return 'account';
}
/**
* {@inheritDoc}
*/
public function me(Request $request)
{
return new AdminResource($request->user());
}
}
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use A2Workspace\LaravelJwt\AuthenticatesUsers;
class AuthController extends Controller
{
use AuthenticatesUsers;
}
use PHPOpenSourceSaver\JWTAuth\JWTGuard;
class AuthController extends Controller
{
use AuthenticatesUsers;
/**
* 回傳認證守衛
*
* @return \PHPOpenSourceSaver\JWTAuth\JWTGuard
*/
protected function guard(): JWTGuard
{
return Auth::guard('custom-api-guard');
}
}
class AuthController extends Controller
{
use AuthenticatesUsers;
/**
* 取得驗證使用者名稱的欄位
*
* @return string
*/
protected function username()
{
return 'username';
}
}