首页 > 解决方案 > 如何在本地存储中传递用户 ID 和 JWT 令牌

问题描述

我目前正在使用LaravelVue框架,并且正在使用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,并将其保留在本地存储中以供使用,并且仅在用户退出当前帐户时才被删除。

提前谢谢。

标签: laravelauthenticationvue.jsjwtlocal-storage

解决方案


在登录功能下方的控制器中创建一个新功能。

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 保存在浏览器的本地存储中,因为这将是一个主要的安全问题。使用此网络服务通过生成的令牌获取任何用户的详细信息。


推荐阅读