php - 使用用户名而不是电子邮件的 JWTAuth 身份验证

标签 php api laravel authentication

有没有什么办法可以在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');

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

最佳答案

我找到了一个方法 here

我们可以从模型(基于自定义字段)中获取用户,例如

//抓取一些用户

$user = User::first();

并手动验证它。

$token = JWTAuth::fromUser($user);

关于php - 使用用户名而不是电子邮件的 JWTAuth 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449202/

相关文章:

php - 多个重写规则导致内部服务器错误

javascript - 确认对话框无法正常工作

json - 解析的 JSON 长时间未在 api 调用上更新

php - 如何设置 Laravel 通知的回复地址?

laravel - laravel 更新后如何删除旧图像?

php - 在php中获取url id并检查它是否存在于数据库中

javascript - onchange 仅适用于表中的第一行

android - 用于英语以外语言的 Google 语音转文本 API

jquery - jQuery连续有多个If语句

javascript - 确定 dropzone.js 中所有文件何时上传成功