A simple library to work with JSON Web Token and JSON Web Signature

Overview

JWT

Gitter Total Downloads Latest Stable Version Unstable Version

Build Status Code Coverage

A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519.

Installation

Package is available on Packagist, you can install it using Composer.

composer require lcobucci/jwt

Documentation

The documentation is available at https://lcobucci-jwt.readthedocs.io/en/latest/.

Supported by Auth0 auth0

If you want to add secure token based authentication to your PHP projects, feel free to check out Auth0's PHP SDK and free plan at auth0.com/developers.

Comments
  • How to use with .p8 file

    How to use with .p8 file

    Hi there,

    The new MapKit JS by Apple uses JWT, however, Apple gives a .p8 certificate which only holds a private key. How can I use this to verify the signature?

    Thanks!

    Question 
    opened by mischasigtermans 24
  • Connect to Apple using .p8 cert file ( PHP 8.1 )

    Connect to Apple using .p8 cert file ( PHP 8.1 )

    Hello!

    Im using this liblary to generate ES256 JWT for Apple to connect with them, but the problem is that generated token is invalid.

    So in summary :

    • I got from them : AuthKey_XXXXXXXXXX.p8 ( as u can see its in p8 format )
    • PHP of my server is 8.1. which means that I'm using this liblary in version : 4.1

    What I did and it didn't work

    • trying to convert .p8, to .pem and generate public key from .pem one, and use this in code below

    My Code (PHP 8.1)

    require 'vendor/autoload.php';
    use Lcobucci\JWT\Configuration;
    use Lcobucci\JWT\Validation\NoConstraintsGiven;
    use Lcobucci\JWT\Signer\Key\InMemory;
    
    $privateKey = InMemory::file(__DIR__ . '/AuthKey_XXXXXXX.pem');
    $publicKey = InMemory::file(__DIR__ . '/AuthKey_XXXXXXX.pub');
    
    $config = Configuration::forAsymmetricSigner(Lcobucci\JWT\Signer\Ecdsa\Sha256::create(), $privateKey, $publicKey );
    
    $now = new DateTimeImmutable();
    
    $token = $config->builder()
        ->issuedBy('XXXXXXXXX')
        ->withHeader('alg', 'ES256')
        ->withHeader('kid', 'XXXXXXXXX')
        ->withHeader('typ', 'JWT')
        ->permittedFor('appstoreconnect-v1')
        ->withClaim('scope', array("GET /v1/apps?filter[platform]=IOS"))
        ->issuedAt($now)
        ->expiresAt($now->modify('+1 hour'))
        ->getToken($config->signer(), $config->signingKey());
    
    $final_token = $token->toString();
    
    
    // And final connecting with Apple because token is generated :
    $url = 'https://api.appstoreconnect.apple.com/v1/apps/';
    $ch = curl_init();
    $header = array();
    $header[] = 'Content-length: 0';
    $header[] = 'Content-type: application/json';
    $header[] = 'Authorization: Bearer '.$final_token;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $head = curl_exec($ch);
    print_r($head);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    

    What I need :

    • generate valid ES256 JWT which will allows me to connect with Apple, based on .p8 file which I have

    Thanks, Jake

    Question 
    opened by cubevis 23
  • Laravel passport broken as a result of #5ce37ae2

    Laravel passport broken as a result of #5ce37ae2

    Hello,

    We're currently using Laravel Passport and it's pulled in JWT 3.4. The standard "/oauth/token" route now longer works as the newly added deprecation messages are interrupting the flow, which were added in:

    https://github.com/lcobucci/jwt/commit/5ce37ae2061942019e21ad5ef3af160cb5a4ad39

    Don't have any more info yet but adding just in case anyone else is experiencing this?

    Invalid 
    opened by compenginecode 22
  • Replaced Token->validate with Validator class handling token validation

    Replaced Token->validate with Validator class handling token validation

    @lcobucci I kept the responsibility for validating in the claim, since they are like value objects and know best how to validate themselves. I'm not sure where to put the error message. In the claim itself?

    Also documentation still needs update in this PR.

    Your comments please?

    Improvement BC-break 
    opened by dannydorfel 22
  • Improve Builder interface methods

    Improve Builder interface methods

    As per @henriquemoody and @Ocramius reviews on #129 we can make things more clear. So let's discuss here to find the best names for with(), canOnlyBeUsedBy() and other method we would like to discuss about.

    Improvement 
    opened by lcobucci 20
  • Encode timestamps as float instead of string

    Encode timestamps as float instead of string

    Currently all timestamps are rendered as strings. Some JWT parsers like auth0/node-jsonwebtoken and jwt.io complain about timestamps formatted as a string. This PR changes this to encode timestamps as float instead of string values.

    Won't Fix BC-break 
    opened by StephenBeirlaen 18
  • Enable integration with third-party signing

    Enable integration with third-party signing

    For those people who may use cloud-based security infrastructure (e.g. Azure Keyvault HSM, Amazon AWS HSM), there is no way to integrate signing with lcobucci/jwt because, for example, your code presently requires people to supply the path to the private key on the local filesystem.

    For avoidance of doubt, I am not saying that you need to code all the API communications ! I am just saying, give me an easy way to (a) get the "string to sign" and (b) supply the signed value back to lcobucci/jwt .... the "black-box" magic in the middle can be done by people's code.

    Hope this makes sense.

    Won't Fix 
    opened by udf2457 18
  • Misuse resistant API

    Misuse resistant API

    Hi, one thing I like very much about PASETO is it's impossible to use it in insecure ways. I'm not talking about JWT RFC flaws, but rather about API that we can and should implement to force a safe usage.

    Here are two examples of lcobucci/jwt:v4 misuse:

    /**
     * 1) Validation missing
     */
    $jwtToken  = (new JwtParser(new JoseEncoder()))->parse($_POST['jwt']);
    loginUser($jwtToken->claims()->get(RegisteredClaims::AUDIENCE));
    
    /**
     * 2) Validation typo
     */
    $jwtToken  = (new JwtParser(new JoseEncoder()))->parse($_POST['jwt']);
    // It should be assert()
    (new Validator())->validate(
        $jwtToken,
        new SignedWith(new Eddsa(), InMemory::base64Encoded('foo'))
    );
    loginUser($jwtToken->claims()->get(RegisteredClaims::AUDIENCE));
    

    For v5 I propose these main BC-breaks:

    1. API MUST require and consume a SignedWith validator in order to parse a JWT Token
    2. API MUST NOT allow claims part to be read nor consumed before the parse call
    3. API MUST allow headers part to be read and consumed before the parse call
    4. API SHOULD accept additional validators to be consumed on parse call
    5. (bonus) API MUST require and consume either a LooseValidAt or StrictValidAt validator in order to parse a JWT Token
    opened by Slamdunk 17
  • Unable to use ECDSA signer on PHP 7.2 (request to update mdanter/ecc dependency)

    Unable to use ECDSA signer on PHP 7.2 (request to update mdanter/ecc dependency)

    To use ECDSA signer it is required to install mdanter/ecc version ~0.3.1. But this extension requires php-mcrypt which was deprecated in PHP 7.1 and was deleted in PHP 7.2. Latest mdanter/ecc (0.5.0) doesn't depend on mcrypt but however it is incompatible and throws an exception: Type error: Argument 1 passed to Lcobucci\JWT\Signer\Ecdsa\KeyParser::__construct() must be an instance of Mdanter\Ecc\Math\MathAdapterInterface, instance of Mdanter\Ecc\Math\GmpMath given, called in /vendor/lcobucci/jwt/src/Signer/Ecdsa.php on line 50

    opened by shakura 17
  • InMemory cannot implement Lcobucci\JWT\Signer\Key

    InMemory cannot implement Lcobucci\JWT\Signer\Key

    Getting this error in latest version please help Fatal error: Lcobucci\JWT\Signer\Key\InMemory cannot implement Lcobucci\JWT\Signer\Key - it is not an interface in /var/www/wmd/current/wmdcore-nightly/vendor/lcobucci/jwt/src/Signer/Key/InMemory.php on line 14

    Laravel version: 8.x JWT: 4.1.5 php: 7.4.28

    Question 
    opened by anshulCoder 16
  • Add Blake2b signature algorithm

    Add Blake2b signature algorithm

    Hi, JWT has never formalized Blake2b as a signing algorithm, hence the BLAKE2B algorithm ID I chose in the code was made up by me and I don't know if this should be merged of not, maybe we could use the @experimental tag on the class, I don't know.

    But if this is nowhere near a standard (in JWT I mean, Blake2b is a standard), why proposing it? Because of this:

    +--------------+-------------------+-----+------+-----+----------+-----------+---------+
    | benchmark    | subject           | set | revs | its | mem_peak | mode      | rstdev  |
    +--------------+-------------------+-----+------+-----+----------+-----------+---------+
    | EddsaBench   | benchSignature    |     | 100  | 5   | 4.359mb  | 20.221μs  | ±2.59%  |
    | EddsaBench   | benchVerification |     | 100  | 5   | 4.359mb  | 45.970μs  | ±0.62%  |
    | Sha256Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 60.589μs  | ±6.34%  |
    | Sha256Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 95.866μs  | ±4.34%  |
    | Sha384Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 61.166μs  | ±1.13%  |
    | Sha384Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 104.584μs | ±0.76%  |
    | Sha512Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 60.701μs  | ±5.33%  |
    | Sha512Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 114.601μs | ±1.13%  |
    | Sha256Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 837.150μs | ±3.02%  |
    | Sha256Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 36.188μs  | ±3.82%  |
    | Sha384Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 803.909μs | ±3.31%  |
    | Sha384Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 38.787μs  | ±3.91%  |
    | Sha512Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 791.626μs | ±1.59%  |
    | Sha512Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 36.873μs  | ±3.04%  |
    | NoneBench    | benchSignature    |     | 100  | 5   | 4.359mb  | 0.123μs   | ±38.90% |
    | NoneBench    | benchVerification |     | 100  | 5   | 4.359mb  | 0.170μs   | ±2.33%  |
    | Sha256Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 2.218μs   | ±8.02%  |
    | Sha256Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 2.410μs   | ±0.20%  |
    | Sha384Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 2.262μs   | ±13.38% |
    | Sha384Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 2.451μs   | ±0.33%  |
    | Sha512Bench  | benchSignature    |     | 100  | 5   | 4.359mb  | 2.285μs   | ±6.95%  |
    | Sha512Bench  | benchVerification |     | 100  | 5   | 4.359mb  | 2.491μs   | ±10.81% |
    | Blake2bBench | benchSignature    |     | 100  | 5   | 4.359mb  | 0.562μs   | ±2.72%  |
    | Blake2bBench | benchVerification |     | 100  | 5   | 4.359mb  | 0.760μs   | ±0.83%  |
    +--------------+-------------------+-----+------+-----+----------+-----------+---------+
    
    Improvement 
    opened by Slamdunk 16
  • Builder fluent interface is confusing

    Builder fluent interface is confusing

    Currently the Token Builder is confusing:

    https://github.com/lcobucci/jwt/blob/602856eb05a0c8e51f0e21925bdc34af372eb582/src/Token/Builder.php#L76-L91

    The name of the method resemble an immutable object, but under the hood it's a fluent interface. All my colleagues get confused too by reading a method like:

    class User
    {
        public function fillJwtToken(JwtBuilder $jwtBuilder): void
        {
            $jwtBuilder->withClaim('user-id', $this->id);
        }
    }
    

    Did the developer forget to return the new object? Or its more a setClaim rather than a withClaim?

    Can we take a direction and forget the other one?

    opened by Slamdunk 3
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Awaiting Schedule

    These updates are awaiting their schedule. Click on a checkbox to get an update now.

    • [ ] Lock file maintenance

    Detected dependencies

    composer
    composer.json
    • php ~8.1.0 || ~8.2.0
    • lcobucci/clock ^3.0.0
    • infection/infection ^0.26
    • lcobucci/coding-standard ^9.0
    • phpbench/phpbench ^1.2.7
    • phpstan/extension-installer ^1.2
    • phpstan/phpstan ^1.9.8
    • phpstan/phpstan-deprecation-rules ^1.1.1
    • phpstan/phpstan-phpunit ^1.3.3
    • phpstan/phpstan-strict-rules ^1.4.4
    • phpunit/php-code-coverage 9.2.23
    • phpunit/phpunit ^9.5.27
    docker-compose
    .github/workflows/composer-json-lint.yml
    github-actions
    .github/workflows/backwards-compatibility.yml
    • actions/checkout v3
    .github/workflows/benchmarks.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    .github/workflows/coding-standards.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    .github/workflows/composer-json-lint.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    .github/workflows/mutation-tests.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    • codecov/codecov-action v3.1.1
    .github/workflows/phpunit.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2
    .github/workflows/release-on-milestone-closed.yml
    • actions/checkout v3
    • laminas/automatic-releases 1.24.0
    • laminas/automatic-releases 1.24.0
    • laminas/automatic-releases 1.24.0
    • laminas/automatic-releases 1.24.0
    • laminas/automatic-releases 1.24.0
    .github/workflows/static-analysis.yml
    • actions/checkout v3
    • shivammathur/setup-php 2.23.0
    • actions/cache v3.2.2

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
  • \Lcobucci\JWT\Configuration::forSymmetricSigner should set up validations.

    \Lcobucci\JWT\Configuration::forSymmetricSigner should set up validations.

    When using a configuration object it makes sense to me to set up constraints when using helpers like forSymmetricSigner.

    public static function forSymmetricSigner(
            Signer $signer,
            Key $key,
            ?Encoder $encoder = null,
            ?Decoder $decoder = null
        ): self {
            $result new self(
                $signer,
                $key,
                $key,
                $encoder,
                $decoder
            );
            $result->validationConstraints[] = new SignedWith($signer, $key);
            return $result;
        }
    

    Of course this will then need to be kept in sync when someone calls setSigner later... So additional point: we should make Configuration immutable.

    opened by SamMousa 0
  • Unencrypted tokens and parser

    Unencrypted tokens and parser

    Hi, first off, love the lib. It's even better in 4.x than it was in 3.x.

    One thing bothers me a bit though, since the interfaces moved around and claims() got moved to the UnencryptedToken interface it left a weird gap in the Parser interface, since it's not possible to get a "proper" decoded token interface via the default implementation. Yeah, it's returning an unencrypted plain token, but it's a bit weird that you can't simply force that.

    I would like to propose a solution to this problem, just like there's a Token interface and UnencryptedToken interface, maybe let's have Parser and UencryptedParser interface? The default implementation could stay the same, the UnencryptedParser interface would simply add a new method - parseUnencrypted(string $jwt): UnencryptedToken or something like that.

    There'd be no modification required on the Parser class, simply changing the interface and having both methods return the same object.

    opened by pkly 17
Releases(4.3.0)
Owner
Luís Cobucci
A software engineer that also loves to share his thoughts about quality, tests and OOP. Member of the PHP community and contributor to open source projects.
Luís Cobucci
Un proyecto que crea una API de usuarios para registro, login y luego acceder a su información mediante autenticación con JSON Web Token

JSON WEB TOKEN CON LARAVEL 8 Prueba de autenticación de usuarios con una API creada en Laravel 8 Simple, fast routing engine. License The Laravel fram

Yesser Miranda 2 Oct 10, 2021
🔐 JSON Web Token Authentication for Laravel & Lumen

Credits This repository it a fork from original tymonsdesigns/jwt-auth, we decided to fork and work independent because the original one was not being

null 490 Dec 27, 2022
Implements a Refresh Token system over Json Web Tokens in Symfony

JWTRefreshTokenBundle The purpose of this bundle is manage refresh tokens with JWT (Json Web Tokens) in an easy way. This bundles uses LexikJWTAuthent

Marcos Gómez Vilches 568 Dec 28, 2022
JSON Web Token (JWT) for webman plugin

JSON Web Token (JWT) for webman plugin Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

 ShaoBo Wan(無尘) 25 Dec 30, 2022
Minimalistic token-based authorization for Laravel API endpoints.

Bearer Minimalistic token-based authorization for Laravel API endpoints. Installation You can install the package via Composer: composer require ryang

Ryan Chandler 74 Jun 17, 2022
Making Laravel Passport work with Lumen

lumen-passport Making Laravel Passport work with Lumen A simple service provider that makes Laravel Passport work with Lumen Dependencies PHP >= 5.6.3

Denis Mysenko 651 Dec 1, 2022
PHP Client and Router Library for Autobahn and WAMP (Web Application Messaging Protocol) for Real-Time Application Messaging

Thruway is an open source client and router implementation of WAMP (Web Application Messaging Protocol), for PHP. Thruway uses an event-driven, non-blocking I/O model (reactphp), perfect for modern real-time applications.

Voryx 662 Jan 3, 2023
Basic Authentication handler for the JSON API, used for development and debugging purposes

Basic Authentication handler This plugin adds Basic Authentication to a WordPress site. Note that this plugin requires sending your username and passw

WordPress REST API Team 667 Dec 31, 2022
This library extends the 'League OAuth2 Client' library to provide OpenID Connect Discovery support for supporting providers that expose a .well-known configuration endpoint.

OpenID Connect Discovery support for League - OAuth 2.0 Client This library extends the League OAuth2 Client library to provide OpenID Connect Discove

null 3 Jan 8, 2022
Laravel web rest api authentication library (PHP).

Webi auth library Laravel web rest api authentication library. Install (laravel 9, php 8.1) First set your .env variables (mysql, smtp) and then compo

Atomjoy 2 Nov 25, 2022
Open source social sign on PHP Library. HybridAuth goal is to act as an abstract api between your application and various social apis and identities providers such as Facebook, Twitter and Google.

Hybridauth 3.7.1 Hybridauth enables developers to easily build social applications and tools to engage websites visitors and customers on a social lev

hybridauth 3.3k Dec 23, 2022
PHP library to verify and validate Apple IdentityToken and authenticate a user with Apple ID.

Sign-in with Apple SDK Installation Recommended and easiest way to installing library is through Composer. composer require azimolabs/apple-sign-in-ph

Azimo Labs 79 Nov 8, 2022
Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use

Introduction Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Official Documentation Documenta

The Laravel Framework 3.1k Dec 31, 2022
Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

Rizky Kurniawan 12 Oct 10, 2022
Slim Auth is an authorization and authentication library for the Slim Framework.

Slim Auth is an authorization and authentication library for the Slim Framework. Authentication is provided by the Zend Framework Zend\Authentication component, and authorization by the Zend Framework Zend\Permissions\Acl component.

Jeremy Kendall 246 Dec 16, 2022
Rinvex Authy is a simple wrapper for @Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

Rinvex Authy Rinvex Authy is a simple wrapper for Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest AP

Rinvex 34 Feb 14, 2022
Braindead simple social login with Laravel and Eloquent.

Important: This package is not actively maintained. For bug fixes and new features, please fork. Eloquent OAuth Use the Laravel 4 wrapper for easy int

Adam Wathan 374 Dec 21, 2022
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Introduction Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs. Official Documentation Documentation for Sanctum

The Laravel Framework 2.4k Dec 30, 2022
How to create a simple auth system with login and signup functionalities in Code-igniter 4.

Codeigniter 4 Authentication Login and Registration Example Checkout the step-by-step tutorial on: Codeigniter 4 Authentication Login and Registration

Digamber Rawat 7 Jan 9, 2023