简体   繁体   中英

laravel 5.1 Auth::check() 500 internal server error afterJWTAuth::attempt($credentials) login

I am creating login api in laravel 5.1 .

I have created user authentication in controller

    try {

        // verify the credentials and create a token for the user

        if (! $token = JWTAuth::attempt($credentials)) {
            $response['error'] = 'true';
            $response['data'] = 'invalid_credentials';
            return response()->json($response);
        }

    } catch (JWTException $e) {
        // something went wrong
        $response['error'] = 'true';
        $response['data'] = 'could_not_create_token';
        return response()->json($response);
    }

    $response['error'] = 'false';

    $response['data'] = ['token'=>$token];
    return response()->json($response);

It is working, and successfully generating token.

but in this code before return, if check login dd(Auth::check()); It throws

Status 500 Internal Server Error

Then here, How can I get user from database after successful login?

I dont really know if Auth::check() will work by default in laravel 5.1 since JWTAUTH and Auth are two different interfaces. so what i do is i have a function that i use to check and get the user details if the user is logged in.

 public function getAuthUser() {
    try {
        if (! $user = JWTAuth::parseToken()->authenticate()) {
            throw new Exception('user_not_found',404);
        }else{
            $data['user'] = $user;
        }

    } catch (TokenExpiredException $e) {
        throw new Exception('token_expired',$e->getStatusCode());
    } catch (TokenInvalidException $e) {
        throw new Exception('invalid_token',$e->getStatusCode());
    } catch (JWTException $e) {
        throw new Exception($e->getMessage(),403);
        throw new Exception('token_absent',$e->getStatusCode());
    }

    // the token is valid and we have found the user via the sub claim
    return $data;
}

check if you done some Log in the function, check if you have the right permission on the relative log file. Log::info may throw the 500 server error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM