Json web signature php

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.

PHP JSON Web Signature Utility

payconiq/php-jws-signature

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.

Читайте также:  Способы создания объектов javascript

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 Json Web Signature Utility

Introduction

A utility used to validate the Json Web Signature sent in the header of a callback request.

This example makes use of an existing Json Web Signature generated in the EXT environment. Passing the jws, environment and callback body will be validated.

Body — The body of the callback request sent by Payconiq.

Jws — The Json Web Signature sent by Payconiq.

Environment — The environment from which the callback was generated. ext for External and prod for Production.

Run the following commands to add the necessary composer libraries.

composer require web-token/jwt-core

composer require web-token/jwt-signature

Add a requirement for the class in your project such as require_once(‘../src/PayconiqJWSUtil.php’);

 require_once '../src/PayconiqJWSUtil.php'; $util = new PayconiqJWSUtil(); $environment = 'ext'; $jws = 'eyJ0eXAiOiJKT1NFK0pTT04iLCJraWQiOiJlcy5zaWduYXR1cmUuZXh0LnBheWNvbmlxLmNvbSIsImFsZyI6IkVTMjU2IiwiaHR0cHM6Ly9wYXljb25pcS5jb20vaWF0IjoiMjAxOS0wNC0wMVQxMTowNTo1OS4wMDhaIiwiaHR0cHM6Ly9wYXljb25pcS5jb20vanRpIjoiMzRhM2JmMjRhZjgzYTVlOSIsImh0dHBzOi8vcGF5Y29uaXEuY29tL3BhdGgiOiJodHRwczovL3dlYmhvb2suc2l0ZS8yOWRmMGYwZi0xNjA3LTQ1MWMtYTI1Ni0zNzQyOGE0MDNlOGEiLCJodHRwczovL3BheWNvbmlxLmNvbS9pc3MiOiJQYXljb25pcSIsImh0dHBzOi8vcGF5Y29uaXEuY29tL3N1YiI6IjVhZDcyYjJmNWZhOWFkMzE4YTc1ODFmZCIsImNyaXQiOlsiaHR0cHM6Ly9wYXljb25pcS5jb20vaWF0IiwiaHR0cHM6Ly9wYXljb25pcS5jb20vanRpIiwiaHR0cHM6Ly9wYXljb25pcS5jb20vcGF0aCIsImh0dHBzOi8vcGF5Y29uaXEuY29tL2lzcyIsImh0dHBzOi8vcGF5Y29uaXEuY29tL3N1YiJdfQ..GpmaYSsRhyrKdkUfuKU6qtTr_n1_jOGa3_nzRLA2A0y3zGn03BHOGssGXuSqXSF-ilgzfEfTj7TfrE-CyaRkXQ'; $payload = ',"currency":"EUR">'; echo 'Is Signature valid? ' . $util->verifyJWS($environment, $jws, $payload);

About

PHP JSON Web Signature Utility

Источник

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.

JSON Web Signature (JWS) PHP implementation

License

gamegos/php-jws

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

JSON Web Signature (JWS) PHP Library

A simple and extensible PHP implementation of JWS based on JWS draft](http://tools.ietf.org/html/draft-ietf-jose-json-web-signature).

gamegos/jwt library is more suitable for a JSON WEB TOKEN(JWT) solution

The recommended way to install gamegos/jws is through Composer.

$headers = array( 'alg' => 'HS256', //alg is required. see *Algorithms* section for supported algorithms 'typ' => 'JWT' ); // anything that json serializable $payload = array( 'sub' => 'someone@example.com', 'iat' => '1402993531' ); $key = 'some-secret-for-hmac'; $jws = new \Gamegos\JWS\JWS(); echo $jws->encode($headers, $payload, $key); //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lb25lQGV4YW1wbGUuY29tIiwiaWF0IjoiMTQwMjk5MzUzMSJ9.0lgcQRnj_Jour8MLdIc71hPjjLVcQAOtagKVD9soaqU
$key = 'some-secret-for-hmac'; //jws encoded string $jwsString = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lb25lQGV4YW1wbGUuY29tIiwiaWF0IjoiMTQwMjk5MzUzMSJ9.0lgcQRnj_Jour8MLdIc71hPjjLVcQAOtagKVD9soaqU'; $jws = new \Gamegos\JWS\JWS(); $jws->verify($jwsString, $key);

If everything is ok you will get an array with ‘headers’ and ‘payload’.

/* Array ( [headers] => Array ( [alg] => HS256 [typ] => JWT ) [payload] => Array ( [sub] => someone@example.com [iat] => 1402993531 ) ) */

You will get one of these exceptions if something bad happens.

If you only want to parse jws string without signature verification you can use decode method.

Currently these algorithms are supported.

alg Parameter Digital Signature or MAC Algorithm
HS256 HMAC using SHA-256
HS384 HMAC using SHA-384
HS512 HMAC using SHA-512
RS256 1 RSASSA-PKCS-v1_5 using SHA-256
RS384 1 RSASSA-PKCS-v1_5 using SHA-384
RS512 1 RSASSA-PKCS-v1_5 using SHA-512
none No digital signature or MAC performed

See JWA Cryptographic Algorithms for Digital Signatures and MACs page for full list of defined algorithms for JWS.

  • InvalidSignatureException
  • MalformedSignatureException
  • UnspecifiedAlgorithmException
  • UnsupportedAlgorithmException

Extending: Adding New Signature/MAC Algorithm

Create an algorithm class that implements \Gamegos\JWS\Algorithm\AlgorithmInterface.

//example NoneAlgorithm class NoneAlgorithm implements \Gamegos\JWS\Algorithm\AlgorithmInterface < public function sign($key, $data) < return ''; > public function verify($key, $data, $signature) < return (string) $signature === ''; > >
//. $jws = new \Gamegos\JWS\JWS(); $jws->registerAlgorithm('my-new-algorithm', new NoneAlgorithm());

Now you can use my-new-algorithm as a usual ‘alg’ parameter.

Источник

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.

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; 

Источник

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