微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用用户名而不是电子邮件进行JWTAuth身份验证

有没有办法在laravel jwt-auth中使用用户名(或任何自定义列)而不是电子邮件进行身份验证?

这是现有的代码

public function authenticate(Request $request)
{
    $credentials = $request->only('email','password');

    try {
        // 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
        return response()->json(['error' => 'Could_not_create_token'],500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}

我想做这样的事

$credentials = $request->only('username','password');

一种方法是将用户名放在电子邮件列中,但这是一个糟糕的解决方案.

解决方法

Looking around,看起来可以通过设置凭证来实现这一点,例如$credentials = $request-> only(‘username’,’password’);.

所以它看起来像这样:

public function authenticate(Request $request)
    {
        // grab credentials from the request
        //$credentials = $request->only('email','password');
        // Change email to username
        $credentials = $request->only('username','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
        return response()->json(compact('token'));
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐