# Lumen8 で JWT ユーザー認証
Lumen はphp artisan make:authコマンドありません。
make で作成できるのが、migration と seeder だけ
# make users migration
php artisan make:migration create_users_table
database/migrations/*_createusers_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
php artisan migrate
migrate コマンドあたり
- migrate
- migrate:fresh
- migrate:install
- migrate:refresh
- migrate:reset
- migrate:rollback
- migrate:status
# Database seed
database/seeders/DatabaseSeeder.php コメントアウト解除
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call('UsersTableSeeder');
}
}
database/seeders/UsersTableSeeder.php 新規作成
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::factory()->count(1)->create();
}
}
php artisan db:seed --class=UsersTableSeeder
Class UsersTableSeeder does not exist
composer dump-autoload 実行してからもう1回やると、正常に実行されます
# JWT 構築
# configディレクトリ使えるように
composer require chuckrincon/lumen-config-discover
# jwt-authライブラリインストール
composer require tymon/jwt-auth
# JWT_SECRETキー作成
php artisan jwt:secret
# bootstrap/app.php
$app->withFacades(); // コメントを外す
$app->withEloquent(); //コメントを外す
// コメントを外す
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AppServiceProvider::class); // コメントを外す
$app->register(App\Providers\AuthServiceProvider::class); // コメントを外す
$app->register(App\Providers\EventServiceProvider::class); // コメントを外す
// tymon/jwt-auth登録
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
// configディレクトリ使えるように
$app->register(Chuckrincon\LumenConfigDiscover\DiscoverServiceProvider::class);
# config/auth.php ファイル新規作成
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
]
];
# app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
# register login リクエスト
ユーザー登録 POST リクエスト
http://localhost:8000/register
{
"name": "Kris Little",
"email": "agislason@example.com",
"password": "abc123",
"password_confirmation": "abc123"
}
ログイン POST リクエスト
http://localhost:8000/login
{
"name": "Kris Little",
"email": "agislason@example.com"
}
マイページ表示 GET リクエスト
http://localhost:8000/me
Authorization Type : Bearer Token
ログインの戻りトークンをセット
{
"id": 1,
"name": "Kris Little",
"email": "agislason@example.com",
"created_at": "2021-06-02T09:56:20.000000Z",
"updated_at": "2021-06-02T09:56:20.000000Z"
}