使用JWT Auth Credential(用户名/电子邮件)的Laravel API



我正在使用laravel和JWT Auth将我的laravel项目连接到移动设备,这是我在laravel 的api控制器

public function login(Request $request) {
    $credentials = $request->only('email', 'password');
    try {
        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }
    // all good so return the token
    $user = Sentry::authenticate($credentials, false);
    return response()->json([
        'code' => '200',
        'message' => 'success',
        'last_updated' => $user->updated_at->format("Y-m-dTH:i:sZ"),
        'data' => [
            'id' => $user->id,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'username' => $user->username,
            'token' => $token
        ]
    ]);
}

但是如何使用此JWT设置使用电子邮件或用户名的凭据?

如果您使用的是"tymon/jwt-auth"包,那么您只需将user对象传递给JWTAuth类和bam!,您可以获得JWT令牌作为回报,您可以使用该令牌让用户通过该应用程序。

$user = User::where('email', $email)
->orWhere('username', $username)
->first();
$token = null;
if (!$token = JWTAuth::fromUser($get_info)) {
   return $this->respondInternalError( 'Can't generate the JWT token right now, try again later!', 'object', 400);
}
return response()->json([
    'code' => '200',
    'message' => 'success',
    'last_updated' => $user->updated_at->format("Y-m-dTH:i:sZ"),
    'data' => [
        'id' => $user->id,
        'first_name' => $user->first_name,
        'last_name' => $user->last_name,
        'email' => $user->email,
        'username' => $user->username,
        'token' => $token
    ]
]);

您可以使用电子邮件或以下格式登录

public function login(Request $request)
    {
          //validate incoming request
        $this->validate($request, [
            'email_phone' => 'required|string',
            'password' => 'required|string',
        ]);
        try {
            $login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
            // return $login_type;
            $credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
            if (! $token = Auth::attempt($credentials)) {
                return response()->json($this->customResponse("failed", "Unauthorized"), 401);
            }
            return $this->respondWithToken($token);
        } catch(JWTException $e) {
            return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
        }
    }

最新更新