Giter Club home page Giter Club logo

jwt's Introduction

jwt's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwt's Issues

Extract documentation from README.md

In order to improve the readability of the documentation let's split it into multiple files under doc folder.

  • Provide some introduction about claims
  • Provide some examples on what goes on server and client sides

Method to extract payload?

Does it make sense to have a helper method that extracts the payload claims that don't include: iss, aud, jti, iat, nbf, exp? Something like the following:

$token->getPayload(); // Retrieves the custom claims

//Instead of having to do
$uid = (string) $token->getClaim('id');
$custom = (string) $token->getClaim('custom');

$data->setCurrentTime?

Can you elaborate on why you're doing the following? I'm a bit confused. Shouldn't I be able to validate the token using $data->setCurrentTime(time());? Based on the current vs. the expiration time.

$data->setCurrentTime(time() + 4000); // changing the validation time to future

openssl_pkey_get_details() expects parameter 1 to be resource, boolean given

This code from the readme:

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;

$signer = new Sha256();

$token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
                        ->setAudience('http://example.org') // Configures the audience (aud claim)
                        ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
                        ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
                        ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
                        ->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)
                        ->set('uid', 1) // Configures a new claim, called "uid"
                        ->sign($signer, 'testing') // creates a signature using "testing" as key
                        ->getToken(); // Retrieves the generated token

Is causing this exception:

ErrorException: openssl_pkey_get_details() expects parameter 1 to be resource, boolean given

I have the extension installed / enabled. Is this a problem on my end? I am requiring version 3.1 of lcobucci/jwt.

Thanks for writing this library. Besides this issue it has been great!

Decoder is turning objects into arrays

The lib is converting objects into arrays instead of instances of stdClass (by calling json_decode($json, true)).

This will cause some troubles when we're validating a token that have an empty object inside a claim. I think we should remove that true parameter and receive the stdClass to prevent this thing.

Is anyone against this?

Class Hmac not found in Sha256

I get the following errors when I try to use the Sha256 interface:

Fatal error: Class 'Lcobucci\JWT\Signer\Hmac' not found in C:\wamp\www\examples\jwt-master\src\Signer\Hmac\Sha256.php on line 19

I include the following files:
include('jwt-master/src/Builder.php');
include('jwt-master/src/Signer/Hmac/Sha256.php');

Am I doing something wrong here? I'm fairly new to namespaces.

can we invalidate a token when user logout?

I have been using this library for the last 2 week. Its working perfectly fine. I have one question about how can we invalidate a token we already created when user logout ?

Thanks

Move to PHP 7

Since we're planning to break the BC in v4 I believe that we can push this forward and have a better API.

need to set 'x5t' in header

Hi! I am creating a PHP application that will read/write to my organizations office 365 calendar's. In order to get a valid authentication token to use in the Calendar API, I need to do send a POST request to the token issuing authority, containing a JSON Web Token signed with a private x509 key. A certificate thumbprint of the public key needs to be set as the value of the x5t key in the JWT header, if not I'm getting the following error:

Invalid JWT token. No certificate thumbprint specified in token header.

Can I modify the headers with this library? I've checked, and I cannot find a way. If not, do you plan to support it?

Continuous Integration settings

I see in composer.json file other dependencies on require-dev, so you have:

  • PHP_Codesniffer
  • PHPMD

Usually those tools are not something you should use o define if a code is valid or not but they are great to measure the quality of the code.
I have been using scrutinizer for a long I think it's a great tool and it has its own tool for code analysis but also it has support to tools like PHP_Codesniffer, PHPMD, PHPLOC and such.
If you like the idea I can sent you a pull request with the Scrutinizer set up.

JWT intro usage

Hi,

Started playing with jwt and for various reasons ended up writing a selfcontained demo of using jwt+cookies as a drop-in replacement for session auth (see https://gist.github.com/killua-eu/d45ac9a7c8073f24876b). Luis, would you mind looking at the code and pointing out obvious fallacies + best practices according to your experience? I'd like to post the code somewhere more public to make things easier with jwt.

thanks, Pavel

p.s.: Should you at some point want a demo dir for jwt, feel free to tweak the gist and use it as you see fit.

Signer factory?

I'm filing this issue mostly to feel out interest in and/or likelihood of acceptance of a simple factory implementation for Signer implementations if I were to submit a PR for one.

There's a factory for Claims, so it seems like there's some precedent for this.

This Signer factory would essentially resolve short algorithm names, such as those used by the Firebase JWT implementation, to Signer instances, and allow users to add their own custom Signer implementations.

Token Validation API

In my opinion, the current Validation API can be greatly improved:

$data = new ValidationData();
…
$token->validate($data) // returns bool
  1. returning true resp. false isn't very useful; returning a list of constraint violations (i.e. Errors or similar) would be more helpful, e.g. like Symfony and Java do.
  2. token objects should not be responsible for validation; this violates many design principles (e.g. SRP): Changes in the validation process –like I suggest under item 1. – causes changes in the Token class. IMO, using some Validator class would be a much better option.

Reorganize signers namespace

Would be a lot better if the HMAC-SHA* had a separated namespace.

We should things move from Lcobucci\JWT\Signer\Sha256 to Lcobucci\JWT\Signer\Hmac\Sha256.

Support token compression

JWT tokens can be quite long: adding some basic gzip (or better) support to compress their contents/signature would be a plus.

Doesn't seem like it's part of the spec for now, though: dgrijalva/jwt-go#102 (comment)

Maybe a good idea to push back to the spec here?

Simplify and improve Token

Since #21 is introducing a new major release we can change somethings of this class:

  • Rename Token::header to Token::headers (this change should be applied on Builder as well);
  • Rename Token::getHeader() to Token::getHeaders();
  • Introduce Token::getHeader($name) to return a single header;
  • Remove Token::getSignature() (I just don't know why I've created this method, just useless for lib users);

Any thoughts?

The easiest is not always the safest...

To make things easier to the end user of the library I've followed some aspects from another libs, and the Token::verify() was one of them, but after reading this article I think we should change some things (for good).

  • Remove Signer from Signature (and change the BaseSigner);
  • Remove Signer\Factory (and change the Parser);
  • Pass signer on Token::verify() (to validate if the alg header matches) and the Signature::verify() (to see if the signature was created by that signer with the expected key);

Those changes are easy to do and will simplify things (yes Parser I'm talking to you), but since is a BC break I'm moving it to next major release (3.0.0).

Do you guys have any consideration about this?

Keychain deprecated

Is it normal, the class Keychain is deprecated ?

"@deprecated Since we've removed OpenSSL from ECDSA there's no reason to use this class"

I use this class with RSA encryption like in your documentation page , is it an error ?

Thanks for your answer.

README Comment Typo

I think you have a type in the README where you're setting the expiration dates. I'm thinking it should read:

->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)

Side note: Nice work on the library.

ECDSA signing/verification does not work

I was testing if your ECDSA JWT validation works correctly, but couldn't get it to work.

This is the example I used:

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Keychain; // just to make our life simpler
use Lcobucci\JWT\Signer\Ecdsa\Sha512; // you can use Lcobucci\JWT\Signer\Ecdsa\Sha256 if you're using ECDSA keys
use Lcobucci\JWT\Parser;

$keychain = new Keychain();
$token = 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6IndvcmxkIn0.AQx1MqdTni6KuzfOoedg2-7NUiwe-b88SWbdmviz40GTwrM0Mybp1i1tVtmTSQ91oEXGXBdtwsN6yalzP9J-sp2YATX_Tv4h-BednbdSvYxZsYnUoZ--ZUdL10t7g8Yt3y9hdY_diOjIptcha6ajX8yzkDGYG42iSe3f5LywSuD6FO5c';
$token = (new Parser())->parse((string) $token); // Parses from a string
$signer = new Sha512();

var_dump($token->verify($signer, $keychain->getPublicKey("-----BEGIN PUBLIC KEY-----\nMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAcpkss6wI7PPlxj3t7A1RqMH3nvL4\nL5Tzxze/XeeYZnHqxiX+gle70DlGRMqqOq+PJ6RYX7vK0PJFdiAIXlyPQq0B3KaU\ne86IvFeQSFrJdCc0K8NfiH2G1loIk3fiR+YLqlXk6FAeKtpXJKxR1pCQCAM+vBCs\nmZudf1zCUZ8/4eodlHU=\n-----END PUBLIC KEY-----")));

returns false.

Maybe I'm doing something wrong, but I quickly looked over the code and it looks like the ECDSA signing is not implemented according to the JWT RFC. See https://tools.ietf.org/html/rfc7515#appendix-A.3.1.

Also see this issue: jwt/ruby-jwt#84.

Private/public claims validation

The issue #28 remind me of that we actually don't have any way to validate private/public claims.

Of course this is an edge case because most of people will just "store things" in the token and are not expecting to validate a non-registered claim, but anyway this should probably be helpful for someone.

Signer factory deleted !

From a closed issue, the Signer Factory was deleted, for security reasons of course, but i think it still useful for signer creation, so instead of

$signer = new Sha256();
$builder = (new Builder())->sign($signer, 'some key');

we can use a factory

$builder->sign(Factory::create('HS256'), "some key");

for example, it can be helpful when we use a configuration variable to store the signer id, like

$signer = Factory::create(config('jwt.algo'));
...
$builder->sign($signer, "key");

Do we really need to throw an exception when verifying the signature of an unsigned token?

I thinking that just returning false would be good enough and will simplify the code of library users.

Instead of doing:

try {
    if (!$token->verify($signer, $key) || !$token->validate($data)) {
        // do something to tell that the token is unacceptable.
    }
} catch (\BadMethodCallException $e) {
    // do something to tell that the token is unacceptable.
}

Users could do:

if (!$token->verify($signer, $key) || !$token->validate($data)) {
    // do something to tell that the token is unacceptable.
}

Any thoughts?

Catch exceptions when token is being injected

Is there any way to catch specific or multiple exceptions in case of token injection?

In details, when I change a generated token, the lib throws exceptions like:

  • RuntimeException in Decoder.php line 36
  • OutOfBoundsException in Token.php line 110

As a result, I cannot proceed to token validation.

Thank you

Validation returning false.

SOLVED: Read below

I'm not sure what I am doing wrong, as I've tried this with the example provided by the page and it was still returning false.

`use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

$signer = new Sha256();

$token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
->setAudience('http://example.com') // Configures the audience (aud claim)
->setId('b2lk2hj3j4', true) // Configures the id (jti claim), replicating as a header item
->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)
->set('uid', 1) // Configures a new claim, called "uid"
->set('user', 'jordan')
->sign($signer, 'secretKey') // creates a signature using "testing" as key
->getToken(); // Retrieves the generated token

$token->getHeaders(); // Retrieves the token headers
$token->getClaims(); // Retrieves the token claims

header("Authorization: Bearer " . $token);

echo $token->getHeader('jti');
echo $token->getClaim('iss');
echo $token->getClaim('uid');

echo $token; // The string representation of the object is a JWT string (pretty easy, right?)

$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer('http://example.com');
$data->setAudience('http://example.com');
$data->setId('b2lk2hj3j4');

var_dump($token->validate($data)); // true, because validation information is equals to data contained on the token`

Setting custom claims causes PHP errors to be thrown.

The reason this was not validating is because ValidationData.php is not set up to handle custom claims. You must edit the file to your liking.

Token validation !

I tried to create a token without Expiration claim, and validate it. the token validate method should return false, but instead it returns true.

$builder = new Builder();
$token = $builder->setSubject(1)->getToken();
$validator = new ValidationData();
$this->assertFalse($token->validate($validator)); // Failed asserting that true is false.

I think ValidationData must validate the Token claims and not the opposite.

Token not validating

See any reason why the following wouldn't validate? Note: I've included the required files, as well.

//Setting the token
//Find the server details
$tokenId    = base64_encode(mcrypt_create_iv(32));
$pieces         = parse_url(Router::url('/', true));
$serverName = $pieces['host']; // Retrieve the server name from config file

$signer = new Sha256();
$token = (new Builder())->setIssuer($serverName) // Configures the issuer (iss claim)
                                        ->setAudience($serverName) // Configures the audience (aud claim)
                                        ->setId($tokenId, true) // Configures the id (jti claim), replicating as a header item
                                        ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
                                        ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
                                        ->setExpiration(time() + 3600) // (1 hour) Configures the expiration time of the token (exp claim)
                                        //->set('sub', $user['User']['email']) // Configures a new claim, called "id"
                                        ->set('id', $user['User']['id']) // Configures a new claim, called "id"
                                        ->set('username', $user['User']['username']) // Configures a new claim, called "username"
                                        ->set('role', $user['User']['role']) // Configures a new claim, called "role"
                                        ->set('banned', $user['User']['banned']) // Configures a new claim, called "role"
                                        ->set('supporter', $user['User']['supporter']) // Configures a new claim, called "role"
                                        ->set('private', $user['User']['private']) // Configures a new claim, called "private"
                                        //->sign($signer, strval(Configure::read('Security.cipherSeed'))) // creates a signature using "cipherSeed" as key
                                        ->getToken(); // Retrieves the generated token
//Validating the token
$decoded = (new Parser())->parse((string) $token); // Parses from a string
$decoded->getHeaders(); // Retrieves the token header
$decoded->getClaims(); // Retrieves the token claims

//Check to make sure the token exists
if(empty($decoded)){
    //return json_decode(json_encode("Unable to parse token."), true);
    CakeLog::error('JwtTokenAuthenticate:_findUser: Unable to parse token.');
    return false;
}

$uid = (string) $decoded->getClaim('id');
if( !$uid ){
    CakeLog::error('JwtTokenAuthenticate:_findUser: Unable to find valid id.');
    return false;
}

$pieces         = parse_url(Router::url('/', true));
$serverName = $pieces['host']; // Retrieve the server name from config file

$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
CakeLog::debug('JwtTokenAuthenticate -> Validating token...');
$data->setIssuer($serverName);
$data->setAudience($serverName);
$data->setId($uid);
//$data->setSigner(strval(Configure::read('Security.cipherSeed')));

$data->setCurrentTime(time()); // changing the validation time
$validated = $decoded->validate($data);
CakeLog::debug('Validated -> ' . $validated);
if ( $validated ) {
    CakeLog::debug('Token validated!');
    //Build a user from the token
    return true;
} else {
    CakeLog::error('Token invalid!');
    return false;
}

How to update or refresh token?

I see alot of stackoverflow answers telling that you have to refresh the token every request so that it wont expire whenever there is an activity. Please let me know if this is okay. If yes, let me know how do it in your library/package thanks.

Dave

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.