ollieread/laravel-jwt

此包已被放弃,不再维护。作者建议使用sprocketbox/laravel-jwt包代替。

dev-master 2017-12-20 10:15 UTC

This package is auto-updated.

Last update: 2020-01-09 10:53:55 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

此包为Laravel认证提供驱动程序,允许开发人员使用JWT(JSON Web Tokens)。

创建此包的原因是市面上真正能实现这一功能的包并不多,而现有的最流行包已经过时,使用了一个已经被废弃的JWT库,并且更新频率不高。除此之外,它并没有完全与Laravel的认证功能集成,并且实现上有些过于复杂。

依赖项

  • Laravel 5.5+
  • PHP 7.1
  • OpenSSL扩展

安装

此包可在Packagist上找到,您可以使用Composer进行安装。

composer require ollieread/laravel-jwt

接下来,您需要发布配置。

php artisan vendor:publish 

要使用JWT进行认证,将驱动设置为jwt,如下所示。

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

配置

由于此包可定制,大部分配置只是为了支持默认实现。配置文件本身包含了每个选项的解释。

选项 描述
key 用于HMAC签名
ttl 令牌应持续的总秒数
ttl_refresh 令牌可以刷新的总秒数(目前未使用)
algo 用于签名令牌的算法类
header_prefix Authorization头部的前缀,通常为bearer。这是唯一硬编码为必需的选项
claims.required 用于验证令牌,确保声明存在
claims.persistent 刷新令牌时使用的声明(目前未使用)

此选项之后的格式如下。

'guards'        => [
    'api' => [
    ],
],

上表中的所有配置选项(或您自己添加的任何选项)都可以在此处按守卫进行覆盖。这允许您为每个守卫使用不同的密钥或算法。

用法

大部分情况下,这与默认认证的方式相同。

登录

登录与使用会话驱动程序的方式相同。

凭证

$credentials = $request->all(['email', 'password']);

if (Auth::attempt($credentials)) {
    $token = Auth::token();
    return $token;
}

您的用户模型实例

$token = Auth::setUser($user)->login();

检查登录状态

Auth::check()

获取当前用户

Auth::user()

令牌生成

此包提供了一个默认实现,但您可以选择全局或按守卫覆盖它。

这个功能没有提供外观,主要是因为我不喜欢使用外观。相反,您可以直接输入Ollieread\JWT\JWT或使用app(Ollieread\JWT\JWT::class)

生成器使用了lcobucci/jwt库提供的构建器,相关文档如下:https://github.com/lcobucci/jwt/blob/3.2/README.md

示例生成器

function (Builder $builder, Request $request, Authenticatable $user, string $guard, ?Token $token): Builder {
    // Get the normalised config for this guard
    $config = $this->normaliseConfig($guard);

    // Build the token
    return $builder
        ->setId(str_random(16))
        ->setIssuer($request->getSchemeAndHttpHost())
        ->setIssuedAt($issuedAt = time())
        ->setAudience($request->getSchemeAndHttpHost())
        ->setExpiration($issuedAt + $config['ttl'])
        ->set('uid', $user->getAuthIdentifier())
        ->set('grd', $guard)
        ->sign(new $config['algo'], $config['key']);
}

全局

要设置默认生成器,使用JWT::setDefaultGenerator()。这个函数接受一个类似于下面的\Closure实例。

// Set the default generator for tokens
$jwt->setDefaultGenerator(the generator);

每个守卫

要设置守卫生成器,使用JWT::setGuardGenerator()。这个函数接受一个引用守卫的字符串和一个类似于下面的\Closure实例。

// Set the default generator for tokens
$jwt->setGuardGenerator('myguard', the generator);

验证

此包提供了一个默认实现,但您可以选择全局或按守卫覆盖它。

这个功能没有提供外观,主要是因为我不喜欢使用外观。相反,您可以直接输入Ollieread\JWT\JWT或使用app(Ollieread\JWT\JWT::class)

lcobucci/jwt库提供了一个验证数据,相关文档如下:https://github.com/lcobucci/jwt/blob/3.2/README.md

示例验证器

function (Token $token, Request $request, string $guard): bool {
    // Get the normalised config for this guard
    $config = $this->normaliseConfig($guard);
    // Check that the required claims are present
    foreach ($config['claims']['required'] as $claim) {
        if (! $token->hasClaim($claim)) {
            return false;
        }
    }
    // Check that the grd claim matches the current guard
    // We don't check for its presence as it's in the default required claims
    if ($token->getClaim('grd') !== $guard) {
        return false;
    }
    // Verify the signature of the token
    if (! $token->verify(new Sha256, $config['key'])) {
        return false;
    }
    // All of the above has passed, now run the validator on it
    $validator = new ValidationData;
    $validator->setIssuer($request->getSchemeAndHttpHost());
    $validator->setAudience($request->getSchemeAndHttpHost());

    // Return the validation result
    return $token->validate($validator);
}

全局

要设置默认验证器,使用JWT::setDefaultValidator()。这个函数接受一个类似于下面的\Closure实例。

// Set the default validator for tokens
$jwt->setDefaultValidator(the validator);

每个守卫

要设置守卫验证器,使用JWT::setGuardValidator()。这个函数接受一个引用守卫的字符串和一个类似于下面的\Closure实例。

// Set the default generator for tokens
$jwt->setGuardValidator('myguard', the validator);

信息

有关JWT的更多信息,请参阅RFC 7519

此包使用lcobucci/jwt包来生成令牌。