项目作者: eljam

项目描述 :
Guzzle Jwt middleware
高级语言: PHP
项目地址: git://github.com/eljam/guzzle-jwt-middleware.git
创建时间: 2016-01-23T11:07:13Z
项目社区:https://github.com/eljam/guzzle-jwt-middleware

开源协议:MIT License

下载


Guzzle Jwt middleware

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

  1. <?php
  2. use Eljam\GuzzleJwt\JwtMiddleware;
  3. use Eljam\GuzzleJwt\Manager\JwtManager;
  4. use Eljam\GuzzleJwt\Strategy\Auth\QueryAuthStrategy;
  5. use GuzzleHttp\Client;
  6. use GuzzleHttp\HandlerStack;
  7. require_once 'vendor/autoload.php';
  8. //Create your auth strategy
  9. $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);
  10. //Optionnal: create your persistence strategy
  11. $persistenceStrategy = null;
  12. $baseUri = 'http://api.example.org/';
  13. // Create authClient
  14. $authClient = new Client(['base_uri' => $baseUri]);
  15. //Create the JwtManager
  16. $jwtManager = new JwtManager(
  17. $authClient,
  18. $authStrategy,
  19. $persistenceStrategy,
  20. [
  21. 'token_url' => '/api/token',
  22. ]
  23. );
  24. // Create a HandlerStack
  25. $stack = HandlerStack::create();
  26. // Add middleware
  27. $stack->push(new JwtMiddleware($jwtManager));
  28. $client = new Client(['handler' => $stack, 'base_uri' => $baseUri]);
  29. try {
  30. $response = $client->get('/api/ping');
  31. echo($response->getBody());
  32. } catch (TransferException $e) {
  33. echo $e->getMessage();
  34. }
  35. //response
  36. //{"data":"pong"}

Auth Strategies

QueryAuthStrategy

  1. $authStrategy = new QueryAuthStrategy(
  2. [
  3. 'username' => 'admin',
  4. 'password' => 'admin',
  5. 'query_fields' => ['username', 'password'],
  6. ]
  7. );

FormAuthStrategy

  1. $authStrategy = new FormAuthStrategy(
  2. [
  3. 'username' => 'admin',
  4. 'password' => 'admin',
  5. 'form_fields' => ['username', 'password'],
  6. ]
  7. );

HttpBasicAuthStrategy

  1. $authStrategy = new HttpBasicAuthStrategy(
  2. [
  3. 'username' => 'admin',
  4. 'password' => 'password',
  5. ]
  6. );

JsonAuthStrategy

  1. $authStrategy = new JsonAuthStrategy(
  2. [
  3. 'username' => 'admin',
  4. 'password' => 'admin',
  5. 'json_fields' => ['username', 'password'],
  6. ]
  7. );

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:

  1. <?php
  2. use Eljam\GuzzleJwt\Persistence\SimpleCacheTokenPersistence;
  3. use Psr\SimpleCache\CacheInterface;
  4. /**
  5. * @var CacheInterface
  6. */
  7. $psr16cache;
  8. $persistenceStrategy = new SimpleCacheTokenPersistence($psr16cache);

Optionnally you can specify the TTL and cache key used:

  1. <?php
  2. use Eljam\GuzzleJwt\Persistence\SimpleCacheTokenPersistence;
  3. use Psr\SimpleCache\CacheInterface;
  4. /**
  5. * @var CacheInterface
  6. */
  7. $psr16cache;
  8. $ttl = 1800;
  9. $cacheKey = 'myUniqueKey';
  10. $persistenceStrategy = new SimpleCacheTokenPersistence($psr16cache, $ttl, $cacheKey);

Custom persistence

You may create you own persistence handler by implementing the TokenPersistenceInterface:

  1. namespace App\Jwt\Persistence;
  2. use Eljam\GuzzleJwt\Persistence\TokenPersistenceInterface;
  3. class MyCustomPersistence implements TokenPersistenceInterface
  4. {
  5. /**
  6. * Save the token data.
  7. *
  8. * @param JwtToken $token
  9. */
  10. public function saveToken(JwtToken $token)
  11. {
  12. // Use APCu, Redis or whatever fits your needs.
  13. return;
  14. }
  15. /**
  16. * Retrieve the token from storage and return it.
  17. * Return null if nothing is stored.
  18. *
  19. * @return JwtToken Restored token
  20. */
  21. public function restoreToken()
  22. {
  23. return null;
  24. }
  25. /**
  26. * Delete the saved token data.
  27. */
  28. public function deleteToken()
  29. {
  30. return;
  31. }
  32. /**
  33. * Returns true if a token exists (although it may not be valid)
  34. *
  35. * @return bool
  36. */
  37. public function hasToken()
  38. {
  39. return false;
  40. }
  41. }

Token key

Property accessor

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

Json Example:

  1. {
  2. "status": "success",
  3. "message": "Login successful",
  4. "payload": {
  5. "token": "1453720507"
  6. },
  7. "expires_in": 3600
  8. }

Library configuration:

  1. $jwtManager = new JwtManager(
  2. $authClient,
  3. $authStrategy,
  4. $persistenceStrategy,
  5. [
  6. 'token_url' => '/api/token',
  7. 'token_key' => 'payload.token',
  8. 'expire_key' => 'expires_in'
  9. ]
  10. );

Default behavior

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

  1. {
  2. token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9..."
  3. }

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

  1. $jwtManager = new JwtManager(
  2. $authClient,
  3. $authStrategy,
  4. $persistenceStrategy,
  5. [
  6. 'token_url' => '/api/token',
  7. 'token_key' => 'access_token',
  8. ]
  9. );

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:

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

Cached token

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

Json example:

  1. {
  2. token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9...",
  3. expires_in: "3600"
  4. }
  1. $jwtManager = new JwtManager(
  2. $authClient,
  3. $authStrategy,
  4. $persistenceStrategy,
  5. [
  6. 'token_url' => '/api/token',
  7. 'token_key' => 'access_token',
  8. 'expire_key' => 'expires_in', # default is expires_in if not set
  9. ]
  10. );

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