简体   繁体   中英

How to get user from JWTAuth with token in laravel 5.5

I'm going to use JWTAuth to create token from a model. So I used this method:

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

In my api routes I have:

Route::post('login', 'AuthController@login');

Route::group([

    'middleware' => 'jwt.auth',
    'prefix' => 'auth'

], function ($router) {

    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::get('me', 'AuthController@me');
});

Now I should have access to get user from JWTAuth. Then I use:

$user = JWTAuth::parseToken()->authenticate();

But it returns false.

You should use like in api.php

Route::post('user', 'UserController@createUser');

and In your controller

public function getAuthUser(Request $request) {
        try {

            if (!$user = JWTAuth::toUser($request->token)) {
                return response()->json(['code' => 404, 'message' => 'user_not_found']);
            } else {

                $user = JWTAuth::toUser($request->token);
                return response()->json(['code' => 200, 'data' => ['user' => $user]]);
            }
        } catch (Exception $e) {

            return response()->json(['code' => 404, 'message' => 'Something went wrong']);

        }
    }

hope this will help you.

If you need to get current userid, from header token then try it. Tested

use Tymon\JWTAuth\Facades\JWTAuth;

   protected function getCurrentUser()
    {
        return JWTAuth::parseToken()->authenticate()->id;
    }

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