firebase / php-jwt Goto Github PK
View Code? Open in Web Editor NEWThis project forked from luciferous/jwt
PHP package for JWT
License: BSD 3-Clause "New" or "Revised" License
This project forked from luciferous/jwt
PHP package for JWT
License: BSD 3-Clause "New" or "Revised" License
I'm trying to use this package with Laravel, but I can't catch an exception. How to do that correctly?
public function render($request, Exception $e)
{
if ($e instanceof DomainException) {
return 'Caught!';
}
return parent::render($request, $e);
}
I am getting this error on trying to validate a token. I explain:
1 - My AngularJS sends a http with credentials, database validates it and generates a token.
2 - AngularJS app stores the JWT token locally.
3 - On navigation the app sends the token to the server for validating expire data.
4 - Server throws this exception on trying to decode the JWT token received.
#0 C:\Server\www\routes\remember.php(17): Firebase\JWT\JWT::decode('eyJ0eXAiOiJKV1Q...', 'QWRhZ2FsIFNpc3R...', Array)
#1 [internal function]: Closure->{closure}(Object(Bullet\Request))
#2 C:\Server\www\vendor\vlucas\bulletphp\src\Bullet\App.php(311): call_user_func(Object(Closure), Object(Bullet\Request))
#3 C:\Server\www\vendor\vlucas\bulletphp\src\Bullet\App.php(195): Bullet\App->_runPath('GET', 'eyJ0eXAiOiJKV1Q...')
#4 C:\Server\www\index.php(39): Bullet\App->run(Object(Bullet\Request))
#5 {main}
Warning: openssl_sign(): supplied key param cannot be coerced into a private key in /home/unitefi2/public_html/phpjwt/src/JWT.php on line 196
Fatal error: Uncaught exception 'DomainException' with message 'OpenSSL unable to sign data' in /home/unitefi2/public_html/phpjwt/src/JWT.php:198 Stack trace: #0 /home/unitefi2/public_html/phpjwt/src/JWT.php(167): Firebase\JWT\JWT::sign('eyJ0eXAiOiJKV1Q...', NULL, 'RS256') #1 /home/unitefi2/public_html/phpjwt/test/test.php(27): Firebase\JWT\JWT::encode(Array, NULL, 'RS256') #2 /home/unitefi2/public_html/phpjwt/test/test.php(38): create_custom_token('8yzfPkGWlifpe0k...') #3 {main} thrown in /home/unitefi2/public_html/phpjwt/src/JWT.php on line 198
I've noticed that the file downloaded by composer is not the same as the last one here in the repository. The file obtained by composer (JWT.php) doesn't have "not before" ($payload->nbf) verification.
I'm using Auth0. I put the the Auth0 issued JWT token and my secret into jwt.io and it verifies sig just fine.
I do have to check the secret base64 encoded
box however.
I have tried both:
$decoded = \Firebase\JWT\JWT::decode($token,$secret,['HS256']);
and
$decoded = \Firebase\JWT\JWT::decode($token,base64_decode($secret),['HS256']);
But I always get SignatureInvalidException
How do I get \Firebase\JWT\JWT::decode()
to accept a base64 encoded secret key?
PHP 5.5.23, php-jwt v3.0.0
Would be nice to be able to decode the jwt without needing to verify the signature.
Eg, if you need to do additional processing when the jwt is expired.
Something like this:
public function decode($jwt, $verify = true)
Apparently there is a missing DomainException.php file. The decode function fails because the DomainException class is not defined.
Hello, first of all, great library and thanks for putting it together.
My question pertains to the RFC-7519 spec for the 'iat' claim and how it is handled in this lib.
4.1.6. "iat" (Issued At) Claim
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Since the spec says this claim is optional and doesn't specify the validity of an 'iat' claim, other than being an NumericDate value, shouldn't the library not enforce validity by default?
I see you can specify a 'leeway' time to account for clock variations and the 'iat' will be checked with this value but doesn't this break the specification? Wouldn't it be better to allow the consumer of the library to specify if the 'iat' claim should be checked outside of the NumericDate value requirement?
Any ideas why my token auth is giving me this?
<br />
<b>Fatal error</b>: Cannot access property started with '\0' in
<b>[..]/vendor/firebase/php-jwt/Authentication/JWT.php</b>on
line
<b>237</b>
<br />
The only thing I can find on this issue may be related to:
Hi,
We are considering including your library in our application.
Could you please create a tag in packagist in order to have a stable version to include?
Thanks a lot.
When using a library such as this in a larger framework its very nice to have a properly namespaced file. Could I suggest that you namespace under your Git name:
namespace Firebase;
would be adequate and would insure that there would be no confusion between this library and anything using it that might out of necessity share its name.
This is the line in question. I'm sure I'm missing something out of ignorance...
I want to build secure api application consult of http://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel-and-angularjs
As far as work great in my routes.php, but when i move this code in my controller
if ( ! $token = JWTAuth::attempt($credentials)) {
return Response::json(false, HttpResponse::HTTP_UNAUTHORIZED);
}
it throw exception like this
Non-static method Tymon\JWTAuth\JWTAuth::attempt() should not be called statically, assuming $this from incompatible context
If you know what is happened , can you tell me what can i do ?
Should i put all the code in my routes?
thanks!
I would like to be able to verify a RS512 / sha512 signature with an RSA PUBLIC KEY. Do you have any plans to support that or is there some way to do it now. Thanks.
Please replace all use of JWT::
with self::
, since I don't see any reason to use JWT in place of self here.
(edited by Kato: Please keep the commentary civil and productive. Cheers.)
A few PR's building up but no commits or merges to main project for a while? Just wondering whether I stop waiting and use my own fork. Cheers, Joseph
Is it possible to have specific exceptions so they can be caught accordingly?
At the moment I am having todo the following:
catch (UnexpectedValueException $e)
{
if($e->getMessage() == "Expired Token") {
// Logic Here
} else {
throw $e;
}
}
Instead I propose the following:
Declare an exception class (i.e. Exceptions.php)
class ExpiredTokenException extends \UnexpectedValueException {}
Handle it in the code
if (isset($payload->exp) && time() >= $payload->exp){
throw new ExpiredTokenException('Expired Token');
}
Catch It
catch (JWT\Exceptions\ExpiredTokenException $e)
{
// Logic Here
}
This can be caught much easier and would have backwards compatibility with devs using UnexpectedValueException
.
I noticed there was a minor difference on the server generating the JWT and the server decoding it (on an openid connect project) and although the difference is within millisecs, very often the iat verification failed so I had to read up at the documentation and verify there is some recommendation at least for the exp and the nbf. so I've considered adding a leeway time to all time verification.
Sources:
http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
http://openid.net/specs/openid-connect-core-1_0.html#IDToken
I've create a pull request #39 to resolve this issue a while back so I'm not sure if the workflow in this project is to see an issue first before heading for the push requests :)
The releases page doesn't have the latest release marked as "latest", this should be updated, otherwise GitHub collapses newer releases and hides them and it's confusing:
https://github.com/firebase/php-jwt/releases
I was trying to decode the generated token using decode function of https://github.com/firebase/php-jwt library.
Here is my code. I have defined private key in my configuration file using following line.
define("FIREBASE_PRIVATE_KEY","-----BEGIN PRIVATE KEY-----\nMY_VERY_VERY_LONG_KEY\n-----END PRIVATE KEY-----\n");
Here is the code to decode token.
JWT::decode($token, FIREBASE_PRIVATE_KEY, array('RS256'));
This code throws following exception.
openssl_verify(): supplied key param cannot be coerced into a public key
Can anyone suggest a solution to this?
There's an issue in some versions of PHP 5.5 where JSON_BIGINT_AS_STRING isn't implemented properly:
json_decode(): option JSON_BIGINT_AS_STRING not implemented
firebase/php-jwt/Firebase/PHP-JWT/Authentication/JWT.php(137): json_decode('{"typ":"JWT","a...', false, 512, 2)
I have been trying to fix this since quite a while now. After my token expires, I get this exception:
PHP Fatal error: Class 'ExpiredException' not found in C:\wamp...\php-jwt-master\src\JWT.php on line 119.
I tried adding the use statement to explicitly use the ExpiredException class, but it still gives me this error. I am trying to redirect the user by comparing the exp claim against the current time.
I put in an associative array:
$token = array(
"id" => $user['id'],
"username" => $user['username'],
"email" => $user['email'],
"realname" => $user['realname'],
"expires" => time() + (24 * 60 * 60)
);
$token = JWT::encode($token, token_secret);
and when I decode, I get an object:
$profile = JWT::decode($token, token_secret);
print_r($profile);
stdClass Object
(
[id] => 1
[username] => stephen
[email] => [email protected]
[realname] => stephen smith
[expires] => 1404683315
)
Is this intentional? Right now I'm just casting it to array, but I think it would be good if it decoded to exactly what was put in?
Hello all, I have a problem in verifying the following signature in php-jwt, it is successfully verified using jwt.io website, the problem appears just when I try to verify it using php-jwt.
I'm not sure if I missed something, could you tell me for any solution.
eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSldUIn0=.eyJ0aW1lIjoxNDI4OTQyMDcxLCJzdHIiOiJrYXJ0YWwiLCJsYW5ndWFnZSI6InRyIn0=.k4ZteQMHOs+43YxakNjuDfqevgFSmgwEykrgHxO1Uic=
Presumably composer.phar was checked in accidentally in e0a75bf? It should be removed and added to .gitignore.
I noticed because my IDE found it and started complaining about duplicate class definitions for things like Symfony\Component\Console\Input\InputOption.
Having autoloader headaches.
Hi
try this token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vd3d3Lmdvb2dsZS5pdCIsImF1ZCI6Imh0dHA6Ly93d3cuZ29vZ2xlLml0IiwidXNlcm5hbWUiOiJhbmRyZWEuYmlzZWxsbyIsInJvbGVzIjpbImNhbkNyZWF0ZUNvbnRlbnQiLCJjYW5EZWxldGVDb250ZW50Il19.JQ_lBPw-YKYWeHGstnKSyOOkAwo3EJMQUTr328YW5ic
and verify with this key 9FFF4CB4B9B23C671D327AA84C2F9
here http://jwt.io/
and everything is good.
but why altering the verify signature this still correct?
for example altering the last "c" with a "d", you will obtain a corret signature. how it is possible?
thanks
hi there,
you might not be aware yet, but a critical vulnerability has been found and published in your JWT lib, see the following links:
https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
http://jwt.io/
File: JWT.php
$key = "secret";
$payload= ["id" => 1, "name" => "foo"];
$jwt = JWT::encode( $payload, $key );
Encoding the payload will genrate this JWT
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6ImZvbyJ9.Q4Kee9E8o0Xfo4ADXvYA8t7dN_X_bU9K5w6tXuiSjlU
The error arise when I add two extra digits to the signature ( and only two digits )
$fake = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwibmFtZSI6ImZvbyJ9.Q4Kee9E8o0Xfo4ADXvYA8t7dN_X_bU9K5w6tXuiSjlUxx";
print_r( JWT::decode( $fake, $key, ['HS256'] ));
The code above will report a warning
Warning: hash_equals(): Expected known_string to be a string, boolean given in vendor/firebasephp-jwt/src/JWT.php on line 237
I get lots of "Unknown JSON error: 5". Why not handle all the potential PHP json decoding errors in handleJsonError
and display the real error instead? Only 1,2,3 seem to be handled currently, while others were added in newer PHP versions.
See potential errors here: http://php.net/manual/en/function.json-last-error.php
Or use http://php.net/manual/en/function.json-last-error-msg.php (for PHP >5.5).
When I encode an array using a private key using JWT::encode($array, $privatekey). I get the encrypted token.
But when I base64_decode that token, the token is totally visible.
For example, below is the token the class generated :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySUQiOiIyZGJhMjg1NC0wZGI0LTdhMDEtODMxNS05YWExNzA5MzQzZWUiLCJ0b2tlbl9leHBpcnkiOjE0NjU5Mzk3NzcsInNlY3JldF9pbmZvIjoibXlfc2VydmVyc19zZWNyZXRfaW5mbyJ9.36a0iYzdcgpyxAQjpqnD3kUUaoUjldDcfcjCKkCHhCk
Now, if someone just gets the token somehow, and just base64 decodes it, they can see the whole info inside the token.
Go ahead and base64 decode it and see for your self.
Please let me know if I need to know something or if Im doing something wrong with the encoding part.
As defined in the JWT Draft, Section 4.1.2 you can add a subject as a claim.
Subjects are StringOrURI
, which means that it can either contain a string value or an RFC 3986 URI.
However, this PHP library does not support validating this claim yet.
Are you working on getting this in the library?
I assume it would be as simple as checking the subject of a token and compare it with an array of whitelisted subjects.
I got this Fatal error: Uncaught exception 'Firebase\JWT\ExpiredException' with message 'Expired token' in
I try to run try and catch, but it still come out Fatal Error.
try{
$decoded = JWT::decode($jwt, $key, array('HS256'));
}catch(\Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
I am using PHP-5.4.36
How to catch this error?
Thanks!
Tim McLean
โ@McLean0
If you wrote a JSON Web Tokens library and haven't heard from me, could you contact me please? #jwt #jws #jose #websecurity #vulnerabilities
Hi,
Thanks for this nice little and useful class. I have just one issue.. Right now the JWT class returns StdClass object instead of a simple array.
I was wondering if we can please have the option to return the object as array as well? Maybe as an option.
It would be great because some functions like array_merge, etc don't support StdClass and make life a bit harder. All that's needed to be done is something like this:
json_decode($input, **true**) inside the jsonDecode function I guess?
Please think about it.
Thanks,
san
P.S. I know we can just typecast the object to (array) but that does not recursively work for nested arrays. The objects inside still remain of StdClass :'(
Should we add JWK support?
I'm getting errors like this sometimes:
Cannot handle token prior to 2015-06-04T06:05:30+0000
The error happens at the same time as the time above.
Why this happens and what I need to do to fix this?
Using HS256 works and produces the token key. but using RS256 throws the below error.
I'm using Google Cloud Compute servers if it makes any difference.
PHP Warning: openssl_sign(): supplied key param cannot be coerced into a private key in /firebase/php-jwt/src/JWT.php on line 183
PHP Fatal error: Uncaught exception 'DomainException' with message 'OpenSSL unable to sign data' in /firebase/php-jwt/src/JWT.php:185\nStack trace:\n#0 /firebase/php-jwt/src/JWT.php(154): Firebase\JWT\JWT::sign('XXX...', 'XXX...', 'RS256')\n#1 /firebase.token.php(56): Firebase\JWT\JWT::encode(Array, 'XXX...', 'RS256')\n#2 /firebase.token.php(58): create_custom_token('MYUSER', false)\n#3 {main}\n thrown in /firebase/php-jwt/src/JWT.php on line 185
Thanks !
2014-06-25 06:54:49 --- EMERGENCY: ErrorException [ 2 ]: json_decode(): option JSON_BIGINT_AS_STRING not implemented ~ APPPATH/classes/JWT.php [ 137 ]
my php version is :
PHP 5.5.9-1ubuntu4.1 (cli) (built: Jun 19 2014 20:53:04)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
so its looks like this line fails :
(version_compare(PHP_VERSION, '5.4.0', '>=') && defined('JSON_BIGINT_AS_STRING'))
Hello,
I wonder if it supports/works with hhvm?
Thanks,
Getting error "Missing claim "kid" in auth header". When I add the key ID to get rid of this error, I get "Invalid claim 'kid' in auth header." - I request you to please let me know if you know something about this. Development has stopped for 2 days because of this issue. Thanks a tonne.
// Prepare payload options
$payload = array_merge(array (
'iss' => $service_email,
'sub' => $service_email,
'aud' => 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
'iat' => $now,
'exp' => $now + ($ttl * 60),
'claims' => array (),
), $options);
// Prepare payload claims
$payload['uid'] = firebase_uid2fbid($uid, TRUE);
$payload['claims'] = array(
'provider' => 'drupal',
);
// Generate token
\Firebase\JWT\JWT::$leeway = 60;
$token = \Firebase\JWT\JWT::encode($payload, $service_key, 'RS256', $service_kid);
Here, the $server_kid = config.private_key_id and $server_email = config.client_email. If this is not an issue, please tell me what is it I am doing wrong.
Hello guys , i'm trying this library and i copy the code on the wiki but when i try to decode the jwt php report me an error.
Type: UnexpectedValueException
Message: Invalid claims encoding
i use slim php framework
you can see the error here http://piller.pillsoft.com/api/1/jwt
hi .
i face with this issue when i trying to decode token that send from retrofit from android in php.
but when i use Firefox rest Client everything is good.
Hi,
When verifying, you're just using ===, which leaves you open to a timing attack.
A constant-time equality test should be used instead, e.g.
$len = min(strlen($a), strlen($b));
$result = 0;
for($i = 0; $i < $len; $i++)
{
$result |= ord($a[$i]) ^ ord($b[$i]);
}
$result |= strlen($a) ^ strlen($b);
return ($result == 0);
This is probably just a doc bug--
README says that this "conforms to the current spec", but the link is to the draft-ietf-oauth-json-web-token-06, not the current RFC 7519.
$allowed_algs is empty and thus Exception "Algorithm not supported" is thrown failing decoding
I'm storing jwt in a storage. of if client request with expired token which is in my storage then I want to reissue a jwt. but problem is how to get payloads from a expired jwt ?
Please, add a better documentation, how to auth an user, make a login and logout with php-jwt. Cause not found nowhere in the web.
I read in a different issue that you did not add namespaces because you were trying to keep compatibility with PHP 5.2. Can I suggest that you break off a new version branch for newer versions of PHP?
Currently, your JWT
class is colliding with another really popular package Twilio PHP.
I feel this library could use some documentation, especially some mention that if the token verification fails, an exception will be thrown. Also an example of code where a try catch block is used to decode a token would help.
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.