Laravel Passport Part 1
目錄
OAuth 2 自 2012 年發布以來,得到大部分廠商支援,同時也有眾多語言和套件誕生--當然,Laravel 也推出自家開發的 OAuth 2 套件,像是今天要講的 Passport。
在開始之前,官方文件有提到另一個自家開發的套件 Sanctum,跟 Passport 一樣是產 token。而這兩者的差異在於:Passport 是使用在 Third-party Authorization 的情境,也就是要發 token 給第三方服務;Sanctum 是用在 SPA,也就是發 token 給第一方的前端。
一開始我們先來看看 Passport,並使用 Laravel 8 做為範例來說明。
快速開始
Laravel 自家 Package 安裝都非常方便,Passport 也一樣。首先先安裝套件:
composer require laravel/passport接著在產 token 過程中,會有必要的基本資料表,所以需要執行 migration:
> php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (79.14ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (41.21ms)
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrated: 2016_06_01_000001_create_oauth_auth_codes_table (54.84ms)
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrated: 2016_06_01_000002_create_oauth_access_tokens_table (64.76ms)
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrated: 2016_06_01_000003_create_oauth_refresh_tokens_table (55.25ms)
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated: 2016_06_01_000004_create_oauth_clients_table (56.00ms)
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table
Migrated: 2016_06_01_000005_create_oauth_personal_access_clients_table (31.33ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (45.03ms)資料表總共建立五個如下:
oauth_access_tokens- 對應 OAuth2 Access tokenoauth_auth_codes- 對應 OAuth2 Authorization Code Grant 定義的code欄位oauth_clients- 對應 OAuth2 Clientoauth_personal_access_clientsoauth_refresh_tokens- 對應 OAuth2 Refresh token
若對 OAuth2 熟悉的話,上面的資料表用途相信都能猜得出來。
接下來官方提到要執行 install 指令:
> php artisan passport:install
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
Client secret: YDBIB90*********************************
Password grant client created successfully.
Client ID: 2
Client secret: Sxhy7Hv*********************************這個指令做了三件事:
- 建立產生 access token 所必要的公私鑰(後面會再討論為何需要)
- 建立 Client 1,做為產 personal access token 用
- 建立 Client 2,做為 Password Grant 用(OAuth 定義的完整名稱為 Resource Owner Password Credentials Grant)
接著在 User Model 上加上 HasApiTokens trait,這代表要將此 Model 作為 Resource Owner 用,並會關聯到上述 Passport 所建立的資料表。
再來是加 route。Passport 有提供一個 method 懶人包,一次處理好。
Passport::routes();最後就是修改 config/auth.ph 設定,把 driver 改成 passport 即可完成。
小總結
Laravel Passport 做的非常方便,幾個步驟就能把最基本的架構完成了。後面有空再來說明客製化的部分。