eljam/guzzle-jwt-middleware

guzzle 6 的 jwt 认证中间件

v1.0.2 2023-04-20 09:50 UTC

This package is auto-updated.

Last update: 2024-09-20 13:17:14 UTC


README

Build Status Code Quality Code Coverage SensioLabsInsight Latest Unstable Version Latest Stable Version Downloads license

介绍

LexikJWTAuthenticationBundle 配合使用效果极佳

安装

composer require eljam/guzzle-jwt-middleware

使用

<?php

use Eljam\GuzzleJwt\JwtMiddleware;
use Eljam\GuzzleJwt\Manager\JwtManager;
use Eljam\GuzzleJwt\Strategy\Auth\QueryAuthStrategy;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

require_once 'vendor/autoload.php';

//Create your auth strategy
$authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

//Optionnal: create your persistence strategy
$persistenceStrategy = null;

$baseUri = 'http://api.example.org/';

// Create authClient
$authClient = new Client(['base_uri' => $baseUri]);

//Create the JwtManager
$jwtManager = new JwtManager(
    $authClient,
    $authStrategy,
    $persistenceStrategy,
    [
        'token_url' => '/api/token',
    ]
);

// Create a HandlerStack
$stack = HandlerStack::create();

// Add middleware
$stack->push(new JwtMiddleware($jwtManager));

$client = new Client(['handler' => $stack, 'base_uri' => $baseUri]);

try {
    $response = $client->get('/api/ping');
    echo($response->getBody());
} catch (TransferException $e) {
    echo $e->getMessage();
}

//response
//{"data":"pong"}

认证策略

QueryAuthStrategy

$authStrategy = new QueryAuthStrategy(
    [
        'username' => 'admin',
        'password' => 'admin',
        'query_fields' => ['username', 'password'],
    ]
);

FormAuthStrategy

$authStrategy = new FormAuthStrategy(
    [
        'username' => 'admin',
        'password' => 'admin',
        'form_fields' => ['username', 'password'],
    ]
);

HttpBasicAuthStrategy

$authStrategy = new HttpBasicAuthStrategy(
    [
        'username' => 'admin',
        'password' => 'password',
    ]
);

JsonAuthStrategy

$authStrategy = new JsonAuthStrategy(
    [
        'username' => 'admin',
        'password' => 'admin',
        'json_fields' => ['username', 'password'],
    ]
);

持久化

为了避免每次 PHP 运行时都请求令牌,您可以将 TokenPersistenceInterface 的实现传递给 JwtManager。默认情况下将使用 NullTokenPersistence

简单的缓存适配器 (PSR-16)

如果您有任何 PSR-16 兼容的缓存,您可以使用它作为持久化处理程序

<?php

use Eljam\GuzzleJwt\Persistence\SimpleCacheTokenPersistence;
use Psr\SimpleCache\CacheInterface;

/**
 * @var CacheInterface
 */
$psr16cache;

$persistenceStrategy = new SimpleCacheTokenPersistence($psr16cache);

可选地,您可以指定 TTL 和缓存键

<?php

use Eljam\GuzzleJwt\Persistence\SimpleCacheTokenPersistence;
use Psr\SimpleCache\CacheInterface;

/**
 * @var CacheInterface
 */
$psr16cache;

$ttl = 1800;
$cacheKey = 'myUniqueKey';

$persistenceStrategy = new SimpleCacheTokenPersistence($psr16cache, $ttl, $cacheKey);

自定义持久化

您可以通过实现 TokenPersistenceInterface 创建自己的持久化处理程序

namespace App\Jwt\Persistence;

use Eljam\GuzzleJwt\Persistence\TokenPersistenceInterface;

class MyCustomPersistence implements TokenPersistenceInterface
{
    /**
     * Save the token data.
     *
     * @param JwtToken $token
     */
    public function saveToken(JwtToken $token)
    {
        // Use APCu, Redis or whatever fits your needs.
        return;
    }

    /**
     * Retrieve the token from storage and return it.
     * Return null if nothing is stored.
     *
     * @return JwtToken Restored token
     */
    public function restoreToken()
    {
        return null;
    }

    /**
     * Delete the saved token data.
     */
    public function deleteToken()
    {
        return;
    }

    /**
     * Returns true if a token exists (although it may not be valid)
     *
     * @return bool
     */
    public function hasToken()
    {
        return false;
    }
}

令牌键

属性访问器

使用属性访问器,您可以将指针指向 JSON 中的某个节点

JSON 示例

{
    "status": "success",
    "message": "Login successful",
    "payload": {
        "token": "1453720507"
    },
    "expires_in": 3600
}

库配置

$jwtManager = new JwtManager(
    $authClient,
    $authStrategy,
    $persistenceStrategy,
    [
        'token_url'  => '/api/token',
        'token_key'  => 'payload.token',
        'expire_key' => 'expires_in'
    ]
);

默认行为

默认情况下,此库假设您的 JSON 响应有一个键 token,类似于以下内容

{
    token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9..."
}

但现在您可以在 JwtManager 选项中更改 token_key

$jwtManager = new JwtManager(
    $authClient,
    $authStrategy,
    $persistenceStrategy,
    [
        'token_url' => '/api/token',
        'token_key' => 'access_token',
    ]
);

授权头类型

一些端点使用不同的授权头类型(Bearer、JWT 等)。

默认值为 Bearer,但您可以在中间件中提供其他类型

$stack->push(new JwtMiddleware($jwtManager, 'JWT'));

缓存的令牌

为了避免多个请求之间的调用过多,存在一个缓存系统。

JSON 示例

{
    token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9...",
    expires_in: "3600"
}
$jwtManager = new JwtManager(
    $authClient,
    $authStrategy,
    $persistenceStrategy,
    [
        'token_url' => '/api/token',
        'token_key' => 'access_token',
        'expire_key' => 'expires_in', # default is expires_in if not set
    ]
);

该捆绑包原生支持 JWT 负载中的 exp 字段