简体   繁体   中英

Tymon JWT: how can I authenticate from authenticated user with another user via his id?

Library: https://github.com/tymondesigns/jwt-auth

I want authenticate / get a new token for another user when I'm authenticated as admin (for example). So, imagine a frontend where you click on an user and get the token for that user (if you are an admin).

So, this is my method:

public function authenticate_as(Request $request)
    {
        $user = auth()->user();
        if ($user && $user->role->role === 'admin') {
            $data = json_decode($request->getContent(), true);
            $user_id = $data['user_id'];

            $repository = new UsersRepository();
            $new_user = $repository->show($user_id);

            //$token = auth()->tokenById($user_id);
            $token = auth()->login($new_user);
            return $this->respondWithToken($token);
        }
        return response()->json([
            'error' => 'Unauthorized'
        ], 403);
    }

You can see my attempts with $token = auth()->tokenById($user_id) and $token = auth()->login($new_user); .

In both cases, authenticated admin user has id == 1 and $user_id is 2. At the end, the payload token that I got has sub == 1, so... I'm newly an admin with another token...

Of course in users table id 2 exists...

So, how can I get a token for another user without knowing his password but knowing his ID?

Edit: The issue coming from some session. Because when I pre-authorize other user (admin), sub for new token has ID of first user, not the newly. Without the previous auth, I have not this issue. So, I need to eliminate all session... Or force Tymon/JWT to forget the current user (but with "logout" I get the blacklisted token exception)...

public function login()
{
    $token = Auth::login(User::find(1));

    return response([
        'status' => 'success',
        'token' => $token,
    ])->header('Authorization', $token);
}

Accordingly, you must save this token or overwrite the existing one. If you store user data on the frontend, after re-authorization you must re-obtain it

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