【问题标题】:Laravel 5.7 Auth with email/username and password using tymon/jwtLaravel 5.7 使用 tymon/jwt 使用电子邮件/用户名和密码进行身份验证
【发布时间】:2019-04-13 00:54:40
【问题描述】:

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

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

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

我的用户控制器@身份验证

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

提前致谢

【问题讨论】:

  • 正在使用哪个版本的 Tymon/JWT 包? 0.5.* 还是 1.0.0?
  • 是1.0.x-dev版本

标签: php laravel rest


【解决方案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);

        }
    }

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 感谢@PeterSowah 提供的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2016-03-19
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多