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

开发技术 作者: 2024-07-03 00:05:01
有没有办法在laravel jwt-auth中使用用户名(或任何自定义列)而不是电子邮件进行身份验证? 这是现有的代码 public function authenticate(Request $request) { $credentials = $request->only('email', 'password'); try { // verify the cr
有没有办法在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'));
    }
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_37566.html