Laravel 5.7使用tymon / jwt使用电子邮件/用户名和密码进行身份验证

时间:2018-11-09 12:46:03

标签: php laravel rest

我正在为我的Laravel 5.7应用程序使用jwt-auth。目前,我允许客户端输入电子邮件和密码作为用户凭据。

但是,我也想让客户输入他们的用户名来代替他们的电子邮件。因此,他们有2个选择:电子邮件或用户名。

如何在我的代码中做到这一点?

我的UserController @ authenticate

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');
    try {
        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json([
                'status' => 401,
                'message' => 'invalid_credentials',
            ], 401);
        }
    } catch(JWTException $e) {
        return response()->json([
            'status' => 500,
            'message' => 'token_creation_failed',
        ], 500);
    }

    return response()->json(compact('token'));
}

预先感谢

2 个答案:

答案 0 :(得分:3)

在您的AuthController中,将其添加到登录方法;

public function login()
{
    $loginField = request()->input('login');
    $credentials = null;

    if ($loginField !== null) {
        $loginType = filter_var($loginField, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        request()->merge([ $loginType => $loginField ]);

        $credentials = request([ $loginType, 'password' ]);
    } else {
        return $this->response->errorBadRequest('What do you think you\'re doing?');
    }

    if (! $token = auth()->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return $this->respondWithToken($token);
}

答案 1 :(得分:1)

这是我的处理方式,用户可以选择电子邮件或电话进行登录。

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

        }
    }