0%

[Laravel]_custom_guard

tags: Laravel6

Step 1 定義 guard

  • 在 AuthServiceProvider 的 boot() 中 定義客製的 guard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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’
1
2
3
4
5
6
7
'guards' => [
'api' => [
'driver' => 'custom-token',
'provider' => 'users',
'hash' => true,
],
],

Step 3 自製身份認證 Middleware

  • 在 Middleware 的 handle function 中 使用 Auth::guard()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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";
}
}

}