Laravel6
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();
才會有值
'guards' => [
'api' => [
'driver' => 'custom-token',
'provider' => 'users',
'hash' => true,
],
],
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";
}
}
}