【发布时间】:2019-09-10 05:19:30
【问题描述】:
我目前正在使用 Laravel 和 Vue 框架,并且我正在使用 JWT auth 进行身份验证。问题是我想将user_id 连同令牌一起传递给本地存储,这样如果我需要在某个地方使用它,我可以通过window.localstorage.getItem('user_id') 轻松访问它。我无法这样做。我是这些技术的新手,请帮助
我已经尝试传递令牌并且它是成功的,但是由于某种原因我无法传递 id。
我的 JWT 验证码是:
public function login(Request $request)
{
$credentials = $request->json()->all();
try{
if (!$token = JWTAuth::attempt($credentials)){
return response()->json(['error'=>'invalid_credentials'], 400);
}
}catch(JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500); // something went wrong whilst attempting to encode the token
}
return response()->json(compact('token'));
}
public function getAuthenticatedUser()
{
try{
if(!$user = JWTAuth::parseToken()->authenticate()){
return response()->json(['user_not_found'], 404);
}
}catch(Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
return response()->json(['token_expired'], $e->getStatusCode());
}catch(Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
return response()->json(['token_invalid'], $e->getStatusCode());
}catch(Tymon\JWTAuth\Exceptions\JWTException $e){
return response()->json(['token_absent'], $e->getStatusCode());
}
return $user;
// \Log::info('user id found'.$userId);
}
我想在用户注册并登录时存储 id 并保留在本地存储中以供使用,并且仅在用户退出当前帐户时才删除。
提前谢谢。
【问题讨论】:
-
您可以通过传递生成的令牌创建一个新的 Web 服务来获取用户详细信息。使用此代码:尝试 { $this->jsondata = JWTAuth::authenticate($request->token); $this->message = '已获取用户详细信息。'; $this->状态=真; } 捕捉 (JWTException $e) { $this->status = false; $this->message = '错误'; } return response()->json([ 'status' => $this->status, 'data' => $this->jsondata, 'message' => $this->message ]);
-
@azm_shah 感谢您的回复..但是你能告诉我我必须把这段代码放在哪里
标签: laravel authentication vue.js jwt local-storage