首页 > 解决方案 > Laravel 和 vue,使用 JWT 注册后自动登录

问题描述

我正在开发一个以 vue 作为前端和 laravel 8 api 的项目。我正在使用 JWT 进行身份验证。我知道必须在用户登录之前生成令牌,但是有没有办法在用户注册后自动登录?

标签: laravelvuejs2vuex

解决方案


用户注册成功后返回token:

/*This is your register function, this is after you succesfully saved the user in the database. 
Remember to use JWTAuth*/

/*YOUR REGISTER LOGIC HERE, THEN*/

if($user->save()){
    $credentials = ["email"=>$user->email,"password"=>password_from_request];
    try{
        if(JWTAuth::attempt($credentials)){
           return $this->respondWithToken($token);
        }
    }
    catch (JWTException $e) {
      // something went wrong whilst attempting to encode the token
        return response()->json(['error' => $e], 500);
    }
}else 
    return $this->userRegisterFailedResponse();
    /*Your custom response in case the register fails*/

您可以在JWT 文档中查看 respondWithToken 函数的实现


推荐阅读