iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
自我挑戰組

後端新手PHP+Laravel筆記系列 第 30

[Day30]註冊登入登出

安裝passport套件

  1. 安裝套件cmd執行以下
    composer require laravel/passport

  2. config/app.php檔案中到providers配置文件數組中註冊 Passport 服務

  3. Passport 服務提供者在框架中註冊了自己的數據庫遷移目錄
    所以要進行migrate
    php artisan migrate

  4. create "personal access" and "password grant"
    php artisan passport:install

  5. 加入身份驗證防護選項
    config\auth.php

    'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
    ],
    
  6. 註冊頒發訪問令牌和撤銷訪問令牌、客戶端和個人訪問令牌所需的路由
    app\Providers\AuthServiceProvider.php

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes(); // 加上
    }
  1. 將輔助方法加入到模型之中
    app\Models\User.php
    引入以下
    use Laravel\Passport\HasApiTokens;
    然後使用
    use HasApiTokens, HasFactory, Notifiable;

創建身分controller

php artisan make:controller AuthController.php

新增登入登出及註冊function

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function signup(Request $request)
    {
        $validateData = $request->all();
        $user = new User([
            'name' => $validateData['name'],
            'email' => $validateData['email'],
            'password' => bcrypt($validateData['password']),
        ]);
        $user->save();
        return response('success', 201);
    }

    public function login(Request $request)
    {
        $validateData = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string'
        ]);
        if (!Auth::attempt($validateData)){
            return response('授權失敗', 401);
        }
        $user = $request->user();
        $tokenResult = $user->createToken('Token');
        $tokenResult->token->save();
        return response(['token'=> $tokenResult->accessToken]);
    }

    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response(
            ["message" => "成功登出"]
        );
    }
}

設定路由

web.php設定路由

Route::post('/signup', 'AuthController@signup'); // 註冊
Route::post('/login', 'AuthController@login'); // 登入
Route::group(['middleware'=>'auth:api'], function(){
    Route::get('/logout', 'AuthController@logout');
});

測試

首先註冊
https://ithelp.ithome.com.tw/upload/images/20210930/20128999evj2PGwdcU.jpg
註冊成功後登入取得token
https://ithelp.ithome.com.tw/upload/images/20210930/20128999lcYBvzdSCr.jpg
將token複製到Bearer Token
https://ithelp.ithome.com.tw/upload/images/20210930/20128999yCHQyPLMeC.jpg
複製完成後才能夠登出,登出後token就失效囉
https://ithelp.ithome.com.tw/upload/images/20210930/20128999fqGn7qYymv.jpg

可以舉一反三,將產品路由放置到auth路由內,這樣只有登入的人才可以取得產品資訊


上一篇
[Day29]Laravel Middleware
系列文
後端新手PHP+Laravel筆記30

尚未有邦友留言

立即登入留言