Laravel JWT Auth让用户登录

Jam*_*mie 13 php jwt laravel-5

是否可以使用https://github.com/tymondesigns/jwt-auth 获取current user?因为现在我只能生成一个令牌(当用户登录时).

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    try {
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    return response()->json(compact('token'));
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*ssi 17

你不需要 Auth::user();

你可以使用的toUser方法JWTAuth.只需将令牌作为参数传递,您将获得用户信息:

$user = JWTAuth::toUser($token);

return response()->json(compact('token', 'user'));
Run Code Online (Sandbox Code Playgroud)

有关更多信息,这是toUser方法:

/**
 * Find a user using the user identifier in the subject claim.
 *
 * @param bool|string $token
 *
 * @return mixed
 */

public function toUser($token = false)
{
    $payload = $this->getPayload($token);

    if (! $user = $this->user->getBy($this->identifier, $payload['sub'])) {
        return false;
    }

    return $user;
}
Run Code Online (Sandbox Code Playgroud)


shi*_*kal 15

您可以获取记录的用户数据.

$credentials = $request->only('code', 'password', 'mobile');
try {
    // verify the credentials and create a token for the user
    if (! $token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'invalid_credentials'], 401);
    }
} catch (JWTException $e) {
    // something went wrong
    return response()->json(['error' => 'could_not_create_token'], 500);
}

$currentUser = Auth::user();
print_r($currentUser);exit;
Run Code Online (Sandbox Code Playgroud)


tom*_*laz 12

您也可以使用JWTAuth::user()方法。

所述user()方法调用在返回的toUser()方法,其本身是一个别名为authenticate()用于认证经由令牌的用户的方法。如果用户已经通过身份验证,则无需再次对其进行身份验证(toUser()确实如此),而是user()可以使用方法来获取经过身份验证的用户。

// $token = JWTAuth::attempt($credentials) was successful...

$user = JWTAuth::user();

return response()->json(compact('token', 'user'));
Run Code Online (Sandbox Code Playgroud)