eljam/guzzle-jwt-middleware 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

eljam/guzzle-jwt-middleware

Composer 安装命令:

composer require eljam/guzzle-jwt-middleware

包简介

A jwt authentication middleware for guzzle 6

README 文档

README

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

Introduction

Works great with LexikJWTAuthenticationBundle

Installation

composer require eljam/guzzle-jwt-middleware

Usage

<?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"}

Auth Strategies

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'],
    ]
);

Persistence

To avoid requesting a token everytime php runs, you can pass to JwtManager an implementation of TokenPersistenceInterface. By default NullTokenPersistence will be used.

Simpe cache adapter (PSR-16)

If you have any PSR-16 compatible cache, you can use it as a persistence handler:

<?php

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

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

$persistenceStrategy = new SimpleCacheTokenPersistence($psr16cache);

Optionnally you can specify the TTL and cache key used:

<?php

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

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

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

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

Custom persistence

You may create you own persistence handler by implementing the 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;
    }
}

Token key

Property accessor

With the property accessor you can point to a node in your json.

Json Example:

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

Library configuration:

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

Default behavior

By default this library assumes your json response has a key token, something like this:

{
    token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9..."
}

but now you can change the token_key in the JwtManager options:

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

Null property accessor

If the response is not in json format (i.e. the response body contains only the token in plain text format), you need to set the property accessor to null:

//Create the JwtManager
$jwtManager = new JwtManager(
    $authClient,
    $authStrategy,
    $persistenceStrategy,
    [
        'token_url' => '/api/token',
    ]
);
//Set property accessor to `null`
$jwtManager->setPropertyAccessor(null);

Authorization Header Type

Some endpoints use different Authorization header types (Bearer, JWT, etc...).

The default is Bearer, but another type can be supplied in the middleware:

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

Cached token

To avoid too many calls between multiple request, there is a cache system.

Json example:

{
    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
    ]
);

The bundle natively supports the exp field in the JWT payload.

eljam/guzzle-jwt-middleware 适用场景与选型建议

eljam/guzzle-jwt-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 760.45k 次下载、GitHub Stars 达 28, 最近一次更新时间为 2016 年 01 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「http」 「Guzzle」 「middleware」 「auth」 「handler」 「jwt」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 eljam/guzzle-jwt-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 eljam/guzzle-jwt-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 eljam/guzzle-jwt-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 760.45k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 28
  • 点击次数: 21
  • 依赖项目数: 4
  • 推荐数: 0

GitHub 信息

  • Stars: 28
  • Watchers: 1
  • Forks: 14
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-01-25