如果有用户登录,我会检查中间件。如果有,那么他就不需要头了。如果用户未登录并处于API调用中,则需要添加头令牌。我在(Auth::check(((中遇到一个问题。工作不正常
public function handle(Request $request, Closure $next)
{
if (!Auth::check()) {
$token = $request->header('APP_KEY');
$from = intval(time() / 3600 - 1);
$to = intval(time() / 3600);
$condition1 = md5('ABCD'.$from);
$condition2 = md5('ABCD'.$to);
if ($token == null) {
return response()->json(['message' =>
'App key not Found or user is not Login '], 401);
} else if ($token == $condition1 || $token == $condition2) {
return $next($request);
} else {
return response()->json(['message' =>
"App Key Not Matched".$condition1], 401);
}
} else {
return $next($request);
}
}
当用户成功登录时,您需要在cookie中设置令牌:
// user login
public function login(Request $request) {
$request->validate([
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6',
]);
$user = User::where('email', $request->email)->first();
if (!$user) {
return response()->json([
'success' => false,
'message' => 'User not found',
], 404);
}
if (!Hash::check($request->password, $user->password)) {
return response()->json([
'success' => false,
'message' => 'Password is incorrect',
], 404);
}
$token = $user->createToken('Laravel Password Grant Client')->plainTextToken;
$cookie = cookie('token', $token, 60 * 24 * 30);
return response()->json([
'success' => true,
'message' => 'User logged in successfully',
])->withCookie($cookie);
}
之后,您必须转到该文件,并在handle方法中添加以下代码。appHttpMiddlewareAuthenticate.php
public function handle($request, Closure $next, ...$guards) {
if ($token = $request->cookie('token')) {
$request->headers->set('Authorization', 'Bearer ' . $token);
}
$this->authenticate($request, $guards);
return $next($request);
}
通过这种方式,当您在SPA中使用登录API时,令牌将存储在浏览器的cookie(httpOnly(中,然后您可以使用其他API,这是受保护的路由,头中没有令牌(这意味着您不必在登录后的任何请求中在头中传递令牌(。
要从服务器和浏览器的cookie中删除令牌,您可以在注销方法中使用下面的代码。
// user logout
public function logout(Request $request) {
$request->user()->tokens()->delete();
$cookie = Cookie::forget('token');
return response()->json([
'success' => true,
'message' => 'User logged out successfully',
])->withCookie($cookie);
}