Laravel JWT 身份验证无法正常工作,$token是假/真



我正在使用Laravel 5.7和"tymon/jwt-auth":"1.0.0-rc.3"进行身份验证。在我注册一个用户后,当我尝试给他打电话时,我总是得到一个布尔值:真或假,而不是令牌。我尝试了在互联网上找到的所有"修复程序",但没有任何效果。我错过了什么?

这是注册方法:

protected function create(array $data)
{
    if ($data['legitimation_id'][0] === 'E') {
        $user_type = 1;
    }
    else if ($data['legitimation_id'][0] === 'P') {
        $user_type = 2;
    }
    $data['user_type'] = $user_type;
    $data['password'] = Hash::make($data['password']);
    $user = User::create($data);
    LegitimationController::delete($data['legitimation_id']);
    return $user;
}
public function register(Request $request) {
    $data = $request->all();
    if ($this->validator($data)->fails()) {
        return $this->sendError('Validation Error.', $this->validator($data)->errors());
    }
    if (mb_substr($data['legitimation_id'], 0, 1) != 'P' && mb_substr($data['legitimation_id'], 0, 1) != 'E' ) {
        return $this->sendError('Validation Error.', array("legitimation_id" => 'Fail'));
    };
    $user = $this->create($data);
    $success = ['first_name' => $user['first_name'], 'last_name' => $user['last_name']];
    return $this->sendResponse($success, 'Succes');
}

这是登录方法:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    $jwt_token = null;
    if (!$jwt_token = auth('api')->attempt($credentials)) {
        $this->sendError("Unauthorized", ['error' => 'Invalid Email or Password'], 401);
    }
    $this->sendResponse(['token' => $jwt_token], "Succes");
}

接口.php

Route::group([
'middleware' => 'cors',
'prefix' => 'v1'
], function () {
    Route::post('register', 'AuthRegisterController@register');
    Route::post('login', 'AuthLoginController@login');
});

身份验证.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

如果您之前使用的是其他身份验证系统而不是 laravel jwt,那么建议您在对 laravel 中的配置文件进行更改后在 laravel 中运行清除缓存命令,例如 config/auth.php

PHP 工匠配置:清除

PHP Artisan Config:Cache

最新更新