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

时间:2015-12-14 10:00:29

标签: laravel jwt

我使用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-d\TH:i:s\Z"),
        'data' => [
            'id' => $user->id,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'username' => $user->username,
            'token' => $token
        ]
    ]);
}

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

2 个答案:

答案 0 :(得分:0)

如果您使用的是"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-d\TH:i:s\Z"),
    'data' => [
        'id' => $user->id,
        'first_name' => $user->first_name,
        'last_name' => $user->last_name,
        'email' => $user->email,
        'username' => $user->username,
        'token' => $token
    ]
]);

答案 1 :(得分:0)

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

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);

        }
    }