iT邦幫忙

第 11 屆 iThome 鐵人賽

1
Software Development

PHP新手30天實戰金流系列 第 34

[ Laravel ] 客製 Auth::guard()

tags: Laravel6

Step 1 定義 guard

  • 在 AuthServiceProvider 的 boot() 中 定義客製的 guard
use Illuminate\Support\Facades\Auth;

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

        Auth::viaRequest('custom-token', function ($request) {
            
            if (!$request->remember_token) {
                return null;
            }else {
                $user =User::where('remember_token', $request->remember_token)->first();
                if ($user) {
                    Auth::login($user);
                    return $user;
                }
                return null;
            }
        });
    }

如果 token 是對的,即有通過 if($user), 要記得Auth::login($user); 這樣之後使用 Auth::user(); 才會有值

Step 2 更改 config/auth.php

  • 將 guards 陣列中 api 的 driver 改為自訂的'custom-token'
'guards' => [
        'api' => [
            'driver' => 'custom-token',
            'provider' => 'users',
            'hash' => true,
        ],
    ],

Step 3 自製身份認證 Middleware

  • 在 Middleware 的 handle function 中 使用 Auth::guard()
    public function handle($request, Closure $next, $role)
    {
        try {
        
            if (Auth::guard('api')->user()) {
                $request->merge(['user' => Auth::user()]);
            
            }else {
                try {
                
                    $credentials = $request->only('name', 'password');
                    if (Auth::attempt($credentials,true)) {
                        $request->merge(['user' => Auth::user()]);
                        return $next($request);
                    }else {
                        return response()->json(['result'=>'The token is unavailable. Please login again.']);
                    }
                    
                } catch (\Throwable $th) {
                    return "attempt error";
                }
            }
            
        }

上一篇
[ Laravel ] Event
系列文
PHP新手30天實戰金流34

尚未有邦友留言

立即登入留言