I am trying to implement authentication and authorization in laravel using
JWT but the problem is when a user gets correct login and token is generated and i get that token from api responce but when i try to get the logged-in user + it returns false when i use auth()->check()
[tried every method] it returns null
here is my code
public function login()
{
echo auth()->check();
$credentials = request(["email", "password"]);
if (!$token = auth()->attempt($credentials)) {
return response()->json(["error" => "Login Details are in corrent"], 400);
}
return response()->json(compact('token'));
}
public function respondWithJson($token)
{
return response()->json([
"token" => $token,
"token_type" => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
public function loggedInUser(Request $request)
{
$token = $request->token;
// echo $token;
// $user = auth()->check();
// $user = JWTAuth::user();
return response()->json(compact('user'));
}
}
i am sending request to loggedInUser()
with token in query string but all in vein
i also used the code from documentation
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(["error" => "invalid Credentials"], 401);
}
} catch (JWTException $ex) {
return response()->json(['error' => 'token cannot be created at this moment'], 404);
}
$user = auth()->user();
return response()->json(compact('token', "user"));
}
public function loggedInUser()
{
try {
if (!$user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return response()->json(compact('user'));
}