2017 © Pedro Peláez
 

library guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

image

eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  • Wednesday, June 27, 2018
  • by eljam
  • Repository
  • 1 Watchers
  • 9 Stars
  • 25,550 Installations
  • PHP
  • 2 Dependents
  • 0 Suggesters
  • 3 Forks
  • 0 Open issues
  • 8 Versions
  • 29 % Grown

The README.md

Guzzle Jwt middleware

Build Status Code Quality Code Coverage SensioLabsInsight Latest Unstable Version Latest Stable Version Downloads license, (*1)

Introduction

Works great with LexikJWTAuthenticationBundle, (*2)

Installation

composer require eljam/guzzle-jwt-middleware, (*3)

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., (*4)

Simpe cache adapter (PSR-16)

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

<?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:, (*6)

<?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:, (*7)

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., (*8)

Json Example:, (*9)

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

Library configuration:, (*10)

$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:, (*11)

{
    token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9..."
}

but now you can change the token_key in the JwtManager options:, (*12)

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

Authorization Header Type

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

The default is Bearer, but another type can be supplied in the middleware:, (*14)

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

Cached token

To avoid too many calls between multiple request, there is a cache system., (*15)

Json example:, (*16)

{
    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., (*17)

The Versions

27/06 2018

dev-master

9999999-dev https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

27/06 2018

v0.5.0

0.5.0.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

15/10 2017

v0.4.1

0.4.1.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

24/11 2016

v0.4.0

0.4.0.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

12/10 2016

v0.3.0

0.3.0.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

13/09 2016

v0.2.1

0.2.1.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

12/09 2016

v0.2.0

0.2.0.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6

26/01 2016

v0.1.0

0.1.0.0 https://github.com/eljam/guzzle-jwt-middleware

A jwt authentication middleware for guzzle 6

  Sources   Download

MIT

The Requires

 

The Development Requires

by Guillaume Cavana

middleware auth jwt http psr7 guzzle handler guzzle6