Laravel 无数据库的 JWT 身份验证

JWT authentication in Laravel without database

我对 Laravel 5.x 中的身份验证有疑问。我一直在专门查看 tymondesigns/jwt-authirazasyed/jwt-auth-guard 包,以在我的 Laravel 应用程序中执行 JSON 网络令牌身份验证令牌处理。

我没有使用任何本地数据库,也不想使用。我在 .env 中为我的 API 的 URL, USERNAME & PASSWORD 设置了环境变量。 Guzzle PHP HTTP 客户端正在做这个技巧,根据需要在 API 和我的应用程序之间连接和返回数据。

但是,我需要在 Laravel 实例中设置身份验证。我 运行 在这里遇到问题,并且 auth 需要数据库连接。

$token = JWTAuth::attempt($credentials)

例外情况:

PDOException in Connector.php line 55: 
SQLSTATE[HY000] [14] unable to open database file
  1. 如何在不使用数据库的情况下使用 JWT?
  2. 如何在 Laravel 内完全关闭数据库连接?

谢谢。


更新:

使用 tymon/jwt-auth, 我已经在路由、内核、中间件等中进行了设置

我成功创建了一个“claim”,但我需要通过对“payload”进行编码来创建令牌。

$this->username = $request->username;

$sub = $this->username;
$iat = time();
$jti = md5($sub . $iat);
$aud = env('APP_URL');

$this->claims = [
    'sub' => $sub,
    'iat' => $iat,
    'exp' => time() + (2 * 7 * 24 * 60 * 60),
    'nbf' => $iat,
    'iss' => 'khill',
    'jti' => $jti,
    'aud' => $aud,
];

$payload = JWTFactory::make($this->claims);

如何获得自定义令牌?

JWTAuth::attempt() 不会帮助您解决这个问题,因为它会在幕后为您访问数据库。您需要一些其他方法来检查环境凭据。

将自定义方法添加到某个 class 某处,该方法将为您执行此操作,或者针对您使用 Guzzle 访问的 API 传递凭据。

代码示例:

public function authenticate($username, $password)
{
    if(!$username === env('USERNAME') or !$password === env('PASSWORD')) {
       // return a message that the user could not be authenticated or false.
    }


    // Generate the JWT token here and store it somewhere. 
}

您应该定义自定义 Authentication Provider 并将其设置在 config/jwt.php.


提供商示例

把这个 class 放在任何你喜欢的地方。

namespace MyNamespace;

use Tymon\JWTAuth\Providers\Auth\AuthInterface;

class MyCustomAuthenticationProvider implements AuthInterface
{
    public function byCredentials(array $credentials = [])
    {
        return $credentials['username'] == env('USERNAME') && $credentials['password'] == env('PASSWORD');
    }

    public function byId($id)
    {
        // maybe throw an expection?
    }

    public function user()
    {
        // you will have to implement this maybe.
    }
}

配置示例

config/jwt.phpproviders数组中,改成:

'auth' => 'Tymon\JWTAuth\Providers\Auth\IlluminateAuthAdapter',

对此:

'auth' => 'MyNamespace\MyCustomAuthenticationProvider',

其他注意事项

  1. 在任何地方使用 env() 函数都不是好的做法。最好在配置文件中使用它,然后在其他任何地方使用 config() 函数。

  2. 您可能还需要重新实现 User Provider

作为快速修复,我决定实施以下自定义代码...

1) 创建了自定义中间件来处理逻辑。

class CustomMiddleware
{
    protected $loginPath = 'login';

    public function handle($request, Closure $next) {
        $logged_in = $request->session()->get('logged_in');

        if (!$logged_in) {
            return redirect()->guest('login')->with('flag','1');
        }

    return $next($request);
    }
}

2) 添加了对中间件的引用 class.

class Kernel extends HttpKernel
{
    protected $routeMiddleware = [
        'custom' => \App\Http\Middleware\CustomMiddleware::class,
    ];
}

3) 添加到 routes.php.

Route::group(['middleware' => ['custom']], function () {
    // Add routes here
}

是的。 您可以使用 tymondesigns/jwt-auth 包创建没有数据库的 jwt 令牌...

为此你必须使用 jwt::encode 方法...

让我解释一下...

首先,您必须将您的凭据放入 .env 文件中... 那么我建议您使用自定义声明 ...

之后您可以使用以下代码创建 jwt 令牌...

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$factory = JWTFactory::customClaims($customClaims);
$token = JWTAuth::encode($payload);

详情请参考下方link

wiki