duanrou5680 2019-07-27 12:14
浏览 252

JWT没有登录用户

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'));
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog