[英]Tymon JWT: how can I authenticate from authenticated user with another user via his id?
Library: https://github.com/tymondesigns/jwt-auth图书馆: 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);
你可以看到我的尝试
$token = auth()->tokenById($user_id)
和$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...在这两种情况下,经过身份验证的管理员用户的 id == 1 和 $user_id 是 2。最后,我得到的有效负载令牌具有 sub == 1,所以......我是新的管理员,拥有另一个令牌......
Of course in users table id 2 exists...当然在用户表 id 2 中存在...
So, how can I get a token for another user without knowing his password but knowing his ID?那么,如何在不知道密码但知道他的 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.
因为当我预授权其他用户(管理员)时,新令牌的 sub 具有第一个用户的 ID,而不是新用户的 ID。 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)...
所以,我需要消除所有会话......或者强制 Tymon/JWT 忘记当前用户(但通过“注销”我得到列入黑名单的令牌异常)......
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
如果在前端存储用户数据,重新授权后必须重新获取
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.