简体   繁体   中英

How to get the $user object when authenticated with JWT on Laravel/Lumen?

I have an application that does authentication with JWT. It is my first time creating one. When I try to get the user object in a function, I can't find a way to do it. Here is my code:

public function getEmail(\Illuminate\Http\Request $request)
{
    $user = \Auth::user();

    return new JsonResponse(['message' => $user->email]);
}

It returns that the $user object is null, probably because the Auth class is related to session authentication. I am using this boilerplate: https://github.com/krisanalfa/lumen-jwt

I have looked into the code but can't find a way to get the user, can somebody help out?

Have you tried using this function?

JWTAuth::user();

According to this Guide for setting up with Lumen

You can get it from request object :

Example routes:

$app->get('/login', function (Request $request) {
    $token = app('auth')->attempt($request->only('email', 'password'));

    return response()->json(compact('token'));
});

$app->get('/me', function (Request $request) {
    return $request->user();
});

寻找了几个小时后,我找到了一个可行的答案:

$user = app('Dingo\Api\Auth\Auth')->user();

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