繁体   English   中英

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

[英]Laravel 5.7 Auth with email/username and password using tymon/jwt

我在 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'));
}

提前致谢

在您的 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);
}

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

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

        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM