安裝 passport
- composer
# 移至 laravel 資料夾內
$ composer require laravel/passport
- providers
config\app.php
'providers' => [
// ...
Laravel\Passport\PassportServiceProvider::class,
],
- migration
$ php artisan migrate
若 migration 失敗, 請參考 Migrate 失敗 修正後再次 migrate
# migrate 結果
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrated: 2016_06_01_000001_create_oauth_auth_codes_table
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrated: 2016_06_01_000002_create_oauth_access_tokens_table
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrated: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated: 2016_06_01_000004_create_oauth_clients_table
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table
Migrated: 2016_06_01_000005_create_oauth_personal_access_clients_table
- 產生 oauth2 加密金鑰
$ php artisan passport:install
- 產生結果
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
Client Secret: l2Gh8IIlFoclQyNHEMsWEF4nMeJppdwHUzCDjvtD
Password grant client created successfully.
Client ID: 2
Client Secret: ds3yKXkfnPbaXcRIeDGpc08bRFIdPwtrSnf3DhUo
- 修改 User Class
app\User.php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
- 修改 AuthServiceProvider
app\Providers\AuthServiceProvider.php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
- 修改 config
config\auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Docs
參考資料