Генерация jwt токена php

How to Create a JSON Web Token Using PHP

JWT security is achieved via the signature which is created by hashing the encoded header and payload and securing this with a secret only known to the author.

When receiving a token from a user the author will then be able to validate the signature by re-hashing the received header and payload with the known secret and checking it matches the received signature. If anyone were to tamper with the header or payload the signatures would not match and authentication would fail.

If you wish to get started quickly with JWTs the ReallySimpleJWT library offers an easy to use interface for generating and validating JSON Web Tokens.

use ReallySimpleJWT\Token; // Generate a token $token = Token::getToken('userIdentifier', 'secret', 'tokenExpiryDateTimeString', 'issuerIdentifier'); // Validate the token $result = Token::validate($token, 'secret'); 

It’s perfect if you need to quickly implement user authentication on a simple API. The library also offers more advanced usage and functionality if you’d like to read the documentation.

How to Build a JSON Web Token in PHP

If you’d like to build your own JWT generator or just learn a little bit more about them the following guide will help. While the examples below are written using PHP the concepts apply to any language so all developers should find them useful. The full script is at the bottom of this guide.

Читайте также:  Код цветной кнопки html

Create the Header and Payload

To begin we need to create header and payload JSON strings. We’ll do this based on two simple arrays each asserting a number of claims about the token. You can read more about claims in the associated RFC. For the header we define the type typ and the algorithm alg claims which are RFC standard claims; for the payload we’ll create our own claim user_id .

// Create token header as a JSON string $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']); // Create token payload as a JSON string $payload = json_encode(['user_id' => 123]); 

Create Base64Url Header and Payload Strings

Next we encode our $header and $payload JSON strings as Base64Url strings. This is slightly different to a standard Base64 string and there is no built in PHP Base64Url method yet. So we have to do a bit of string replace magic which will replace + with — , / with _ and = with » . This is so that the Base64 string is passed within URLs without any URL encoding.

// Encode Header to Base64Url String $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header)); // Encode Payload to Base64Url String $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload)); 

Create the Signature

To create the signature we need to use the hash_hmac() method available in PHP and use the sha256 algorithm. We pass in a concatenated string of the Base64Url encoded header and payload $base64UrlHeader . «.» . $base64UrlPayload . It’s important to note we have to include the dot . between the two strings. We add a secret, ideally a strong one that is longer than twelve characters. The ReallySimpleJWT library enforces this principle, but for our example we don’t need to worry. Finally we force the hash_hmac() method to return the output as binary data.

// Create Signature Hash $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true); 

Base64Url Encode the Signature

Once we have created the signature we simply need to Base64Url encode it as we did with the header and payload.

// Encode Signature to Base64Url String $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature)); 

Create the JSON Web Token

Finally we create the JWT by concatenating the header $base64UrlHeader , payload $base64UrlPayload and signature $base64UrlSignature . Each part of the JWT is separated by a dot.

// Create JWT $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature; // Output eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjN9.NYlecdiqVuRg0XkWvjFvpLvglmfR1ZT7f8HeDDEoSx8 

And that’s it, really easy. You can test the JWT that this code produces on the JWT.io website. The code is below in full and I’d suggest you read the relevant documentation on the JWT site along with the RFC.

You can of course use the ReallySimpleJWT Library if you wish and I will produce a post on validating JWTs in the next week or two. If you have any thoughts or have noticed any mistakes please message me @RobDWaller on Twitter.

The Script

// Create token header as a JSON string $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']); // Create token payload as a JSON string $payload = json_encode(['user_id' => 123]); // Encode Header to Base64Url String $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header)); // Encode Payload to Base64Url String $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload)); // Create Signature Hash $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true); // Encode Signature to Base64Url String $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature)); // Create JWT $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature; echo $jwt; 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A PHP implementation of JWT (JSON Web Token) generator, parser, verifier, and validator

License

miladrahimi/php-jwt

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

PHP-JWT is a package written in PHP programming language to encode (generate), decode (parse), verify and validate JWTs (JSON Web Tokens). It provides a fluent, easy-to-use, and object-oriented interface.

In case you are unfamiliar with JWT you can read Wikipedia or JWT.io.

Add the package to your Composer dependencies with the following command:

composer require miladrahimi/php-jwt "2.*"

The following example shows how to generate a JWT and parse it using the HS256 algorithm.

use MiladRahimi\Jwt\Generator; use MiladRahimi\Jwt\Parser; use MiladRahimi\Jwt\Cryptography\Algorithms\Hmac\HS256; // Use HS256 to generate and parse tokens $signer = new HS256('12345678901234567890123456789012'); // Generate a token $generator = new Generator($signer); $jwt = $generator->generate(['id' => 666, 'is-admin' => true]); // Parse the token $parser = new Parser($signer); $claims = $parser->parse($jwt); print_r($claims); // ['id' => 666, 'is-admin' => true]

HMAC algorithms use symmetric keys. A single key can both sign and verify JWTs. This package supports HS256, HS384, and HS512 of HMAC algorithms. The example mentioned above demonstrates how to use an HMAC algorithm (HS256) to sign and verify a JWT.

RSA algorithms are asymmetric. A paired key is needed to sign and verify tokens. To sign a JWT, we use a private key, and to verify it, we use the related public key. These algorithms can be useful when the authentication server cannot trust resource owners. Take a look at the following example:

use MiladRahimi\Jwt\Cryptography\Algorithms\Rsa\RS256Signer; use MiladRahimi\Jwt\Cryptography\Algorithms\Rsa\RS256Verifier; use MiladRahimi\Jwt\Cryptography\Keys\RsaPrivateKey; use MiladRahimi\Jwt\Cryptography\Keys\RsaPublicKey; use MiladRahimi\Jwt\Generator; use MiladRahimi\Jwt\Parser; // Generate a token $privateKey = new RsaPrivateKey('/path/to/private.pem'); $signer = new RS256Signer($privateKey); $generator = new Generator($signer); $jwt = $generator->generate(['id' => 666, 'is-admin' => true]); // Parse the token $publicKey = new RsaPublicKey('/path/to/public.pem'); $verifier = new RS256Verifier($publicKey); $parser = new Parser($verifier); $claims = $parser->parse($jwt); print_r($claims); // ['id' => 666, 'is-admin' => true]

You can read this instruction to learn how to generate a pair (public/private) RSA key.

In default, the package verifies the JWT signature, validates some of the public claims if they exist (using DefaultValidator ), and parse the claims. If you have your custom claims, you can add their validation rules, as well. See this example:

use MiladRahimi\Jwt\Parser; use MiladRahimi\Jwt\Cryptography\Algorithms\Hmac\HS256; use MiladRahimi\Jwt\Exceptions\ValidationException; use MiladRahimi\Jwt\Validator\Rules\EqualsTo; $jwt = '. '; // Get the JWT from the user $signer = new HS256('12345678901234567890123456789012'); // Add Validation (Extend the DefaultValidator) $validator = new DefaultValidator(); $validator->addRule('is-admin', new EqualsTo(true)); // Parse the token $parser = new Parser($signer, $validator); try < $claims = $parser->parse($jwt); echo $claims; // ['id' => 666, 'is-admin' => true] > catch (ValidationException $e) < // Handle error. >

In the example above, we extended DefaultValidator . This validator has some built-in Rules for public claims. We also recommend you extend it for your validation. The DefaultValidator is a subclass of the BaseValidator . You can also use the BaseValidator for your validations, but you will lose the built-in Rules, and you have to add all the Rules by yourself.

Validators use the Rules to validate the claims. Each Rule determines eligible values for a claim. These are the built-in Rules you can find under the namespace MiladRahimi\Jwt\Validator\Rules :

You can see their description in their class doc-blocks.

Required and Optional Rules

You can add a rule to a validator as required or optional. If the Rule is required, validation will fail when the related claim is not present in the JWT claims.

This example demonstrates how to add rules as required and optional:

$validator = new DefaultValidator(); // Add a rule as required $validator->addRule('exp', new NewerThan(time())); // Add a rule as required again! $validator->addRule('exp', new NewerThan(time()), true); // Add a rule as optional $validator->addRule('exp', new NewerThan(time()), false);

You create your own Rules if the built-in ones cannot meet your needs. To create a Rule, you must implement the Rule interface like the following example that shows the Even Rule which is going to check if the given claim is an even number or not:

use MiladRahimi\Jwt\Exceptions\ValidationException; use MiladRahimi\Jwt\Validator\Rule; class Even implements Rule < public function validate(string $name, $value) < if ($value % 2 != 0) < throw new ValidationException("The `$name` must be an even number."); > > >

Here are the exceptions that the package throw:

  • InvalidKeyException :
    • By Generator and Parser methods.
    • When the provided key is not valid.
    • By Parser::parse() , Parser::verify() , and Parser::validate() methods.
    • When the JWT signature is not valid.
    • By Parser::parse() , Parser::verify() , and Parser::validate() methods.
    • When the JWT format is not valid (for example it has no payload).
    • By Parser::parse() and Parser::validate() methods.
    • When the JSON extracted from JWT is not valid.
    • By Generator::generate() method.
    • When cannot convert the provided claims to JSON.
    • By Generator::generate() method.
    • When cannot sign the token using the provided signer or key.
    • By Parser::parse() and Parser::validate() methods.
    • When one of the validation rules fail.

    PHP-JWT is initially created by Milad Rahimi and released under the MIT License.

    About

    A PHP implementation of JWT (JSON Web Token) generator, parser, verifier, and validator

    Источник

Оцените статью