【问题标题】:How to authenticate user using phone number and OTP instead of password in Laravel API?如何在 Laravel API 中使用电话号码和 OTP 而不是密码对用户进行身份验证?
【发布时间】:2021-11-07 15:53:09
【问题描述】:

我正在为移动应用程序构建一个 API,其中通过 OTP sen 通过 SMS 到移动电话设备实现登录。 用户输入电话号码和发送到设备的 OTP 代码后即可登录。

我想做什么? 我正在尝试使用 otp 代码来验证没有密码的用户。

如何在 laravel 中禁用密码? 最好的方法是什么? 或者如果有办法使用 otp 字段而不是密码进行身份验证。

  public function generateOtp(Request $request)
    {
        $identifier = $request->phone;

        $otp = new Otp();
        $code = $otp->generate($identifier, 6, 15);
 User::create([
           'phone'=>$request->phone,
           'otp'=>$code
        ]);

        //Todo::Send OTP number to sms
        return response()->json(['otp' => $code]);
    }

    public function login(Request $request)

    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required',
            'otp' => 'required|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'data' => $validator->errors()], 400);
        }

        $otp = new Otp();
        $otp = $otp->validate($request->phone, $request->otp);

        if ($otp->status == true) {

            $credentials = [
                'phone' => $request->phone,
            ];

            if (auth()->attempt($credentials)) {

                $user = new UserResource(User::find($user->id));

                $this->revokeTokens($user->id);

                $token = $user->createToken('AccessToken')->accessToken;

                $user->token = $token;

                unset($user->code, $user->id, $user->created_at, $user->updated_at);

                return response()->json(['success' => true, 'code' => 1500, 'user' => $user, 'token' => $token]);

            } else {
                return ResponseHelper::notSuccessful(1502, 'login credentials are wrong');
            }
        }

        if ($otp->status == false) {
            return response()->json(['code'=>2, 'message'=>'OTP Expired. Generate New Code']);
        }

    }

【问题讨论】:

    标签: php laravel authentication one-time-password


    【解决方案1】:

    您需要创建自己的用户提供程序类并更改 auth config 中的默认值

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2020-11-08
    相关资源
    最近更新 更多