laravel + passport 搭建 api 认证系统 (一) 基础应用

2021-07-02 19:11

阅读:334

  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
    。 自定义 申请授权 路由,在后台进行访问认证服务器的认证页面

    注册登录代码:
    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()


评论


亲,登录后才可以留言!