laravel - 如何在本地存储中传递用户 ID 和 JWT 令牌
问题描述
我目前正在使用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,并将其保留在本地存储中以供使用,并且仅在用户退出当前帐户时才被删除。
提前谢谢。
解决方案
在登录功能下方的控制器中创建一个新功能。
public function user_details(Request $request){
try {
$this->jsondata = JWTAuth::authenticate($request->token);
$this->message = 'User details fetched.';
$this->status = true;
} catch (JWTException $e) {
$this->status = false;
$this->message = 'Error';
}
return response()->json([
'status' => $this->status,
'data' => $this->jsondata,
'message' => $this->message
]);
}
不要将 user_id 保存在浏览器的本地存储中,因为这将是一个主要的安全问题。使用此网络服务通过生成的令牌获取任何用户的详细信息。
推荐阅读
- angular - Angular 6中模块声明的意外值
- heroku - Vue-js 内容安全策略
- postgresql - 在 postgresql 上创建的新集群中添加数据库?
- rxjs - 用于多个异步调用的 RxJS 设计模式
- reactjs - 在 React 中排序?
- opencv - 使用 cv2.VideoCapture() 时存储了什么以及在哪里存储?
- javascript - 如何在文档准备好后注入的元素上使用 jquery keyup 事件
- algorithm - Find the all possible multiples( size of n ) of a positive integer k
- compilation - 无法使用库编译
- c - CreateFile() 和 CreateFileA() 有什么区别?