1. 程式人生 > >laravel + passport 搭建 api 認證系統 (一) 基礎應用

laravel + passport 搭建 api 認證系統 (一) 基礎應用

inter app models || 如果 ext length com public

參考文檔:
https://segmentfault.com/a/1190000013514298
https://segmentfault.com/a/1190000012292902
https://laravelacademy.org/post/7083.html
https://laravel-china.org/docs/laravel/5.6/passport/1380#introduction

1.composer create-project laravel/laravel QuanDd ‘5.7.*‘
cd QuanDd
git init
git add . && git commit -m "project init"

git remote add origin [email protected]:black_hat/QuanDd.git
git push -u origin master

配置
    storage 目錄和 bootstrap/cache 賦予讀寫權限

    config/app.php
        ‘timezone‘ => ‘Asia/Shanghai‘
        ‘locale‘ => ‘zh_cn‘

應用密鑰
    php artisan key:generate

數據庫配置 .env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=quandd
    DB_USERNAME=root
    DB_PASSWORD=root

兼容 數據庫 utf8mb4
    app/Providers/AppServiceProvider.php
        use Illuminate\Support\Facades\Schema;

        public function boot(){
            Schema::defaultStringLength(191);
        }

模型管理
    mkdir app/Models
    mv app/User.php app/Models/User.php

    User.php
        namespace App\Models;
    批量修改 User 模型的引用 App\User 替換成 App\Models\User
  1. composer require laravel/passport
    config/app.php providers 數組
    Laravel\Passport\PassportServiceProvider::class,

    php artisan migrate
    php artisan passport:install
    添加 Laravel\Passport\HasApiTokens trait 到 App\Models\User 模型
    在 AuthServiceProvider 的 boot 方法中調用 Passport::routes()

    在配置文件 config/auth.php 中,需要設置 api 認證 guard 的 driver 選項為 passport

    ‘guards‘ => [
    ‘web‘ => [
    ‘driver‘ => ‘session‘,
    ‘provider‘ => ‘users‘,
    ],

        ‘api‘ => [
            ‘driver‘ => ‘passport‘,
            ‘provider‘ => ‘users‘,
        ],
    ],

    第一次部署 Passport 到生產服務器時,可能需要運行 php artisan passport:keys

    配置:
    令牌生命周期
    默認情況下,Passport 頒發的訪問令牌(access token)是長期有效的,如果你想要配置更短的令牌生命周期,可以使用 tokensExpireIn 和 refreshTokensExpireIn 方法,這些方法需要在 AuthServiceProvider 的 boot 方法中調用:
    Passport::tokensExpireIn(Carbon::now()->addDays(15));
    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

  2. 使用
    。 調用 json api 創建 一個認證客戶端,生成 ID 和 secrect
    。 自定義 申請授權 路由,在後臺進行訪問認證服務器的認證頁面

    註冊登錄代碼:
    <?php
    namespace App\Http\Controllers\Api;

        use App\Http\Controllers\Controller;
        use App\Models\User;
        use Illuminate\Http\Request;
        use Illuminate\Support\Facades\Auth;
    
        class AuthController extends Controller
        {
            // register inter for users
            public function register(Request $request){
                if (!$request->has(‘phone‘) || !$request->has(‘passwd‘) || !$request->has(‘captcha‘)) {
                    return json_encode([
                        ‘code‘ => ‘4001‘,
                        ‘msg‘ => ‘手機號|密碼|驗證碼不能為空‘
                    ]);
                }
    
                // 手機號驗證
                if (!preg_match("/^1[345789]\d{9}$/", trim($request->phone))) {
                    return json_encode([
                        ‘code‘ => ‘4002‘,
                        ‘msg‘ => ‘非法手機號‘
                    ]);
                }
    
                // 密碼驗證 6-12  字母數字下劃線
                if (!preg_match("/^[0-9A-Za-z_]{6,12}$/", trim($request->passwd))) {
                    return json_encode([
                        ‘code‘ => ‘4003‘,
                        ‘msg‘ => ‘密碼為6-12位的數字字母下劃線‘
                    ]);
                }
    
                // 驗證碼
                // todo
    
                // 手機號是否已註冊
                if (User::hasExists(trim($request->phone))) {
                    return json_encode([
                        ‘code‘ => ‘4004‘,
                        ‘msg‘ => ‘手機號已註冊,請直接登錄‘
                    ]);
                }
    
                $data = [
                    ‘phone‘ => trim($request->phone),
                    ‘password‘ => bcrypt(trim($request->passwd))
                ];
    
                if (!$user = User::create($data)) {
                    return json_encode([
                        ‘code‘ => ‘5001‘,
                        ‘msg‘ => ‘註冊失敗‘
                    ]);
                }       
    
                return json_encode([
                    ‘code‘ => ‘2000‘,
                    ‘msg‘ => ‘註冊並登錄成功‘,
                    ‘data‘ => [
                        ‘phone‘ => $data[‘phone‘],
                        ‘created_at‘ => $user->created_at->toDateTimeString(),
                        ‘token‘ => $tokenData = $user->createToken(‘Tbk MiniP‘)->accessToken
                    ]
                ]);
            }
    
            // user login interface
            public function login(Request $request){
                if (!$request->has(‘phone‘) || !$request->has(‘passwd‘)) {  
                    return json_encode([
                        ‘code‘ => ‘4001‘,
                        ‘msg‘ => ‘手機號|密碼不能為空‘
                    ]);
                }
    
                if (!preg_match("/^1[345789]\d{9}$/", trim($request->phone))) {
                    return json_encode([
                        ‘code‘ => ‘4002‘,
                        ‘msg‘ => ‘非法手機號‘
                    ]);
                }
    
                if (!Auth::attempt([‘phone‘ => trim($request->phone), ‘password‘ => trim($request->passwd)])) {
                    return json_decode([
                        ‘code‘ => ‘4003‘,
                        ‘msg‘ => ‘登錄失敗,用戶名或密碼錯誤‘
                    ]);
                }
    
                $user = Auth::user();
    
                return json_encode([
                    ‘code‘ => ‘2000‘,
                    ‘msg‘ => ‘登錄成功‘,
                    ‘token‘ => $user->createToken(‘Tbk MiniP‘)->accessToken,
                    ‘data‘ => $user->toArray()
                ]);
            }
    
            // test
            public function test(Request $request){
                var_dump($request->header());die;
                $user = Auth::user();
                var_dump($user->toArray());
            }
        }

    常用方法:
    createToken()
    deleteToken()
    tokenExists()

laravel + passport 搭建 api 認證系統 (一) 基礎應用