Coder Social home page Coder Social logo

yii2-jwt's People

Contributors

anatolyrugalev avatar bizley avatar dependabot[bot] avatar githubjeka avatar nadar avatar sizeg avatar stanfieldr avatar

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

Watchers

 avatar  avatar

yii2-jwt's Issues

[Q] Can you please add support php >=8.0?

Hello, thanks for forking and updating lcobucci package, but can you please add support php8.0? it was problem in origin repo, because he didn't update lcobucci package, is it possible to do it soon please?

[Q] validationConstraints is true?

'validationConstraints' => static fn (\bizley\jwt\Jwt $jwt) {
    $config = $jwt->getConfiguration();
    return [
        new \Lcobucci\JWT\Validation\Constraint\SignedWith($config->signer(), $config->signingKey()),
        new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
            new \Lcobucci\Clock\SystemClock(new \DateTimeZone(\Yii::$app->timeZone)),
            new \DateInterval('PT10S')
        ),
    ];
}

$config->signingKey()

it's true?

If this signingKey() is in this case,
PrivateKey is accessed by the LCobucci\JWT\Signer\OpenSSL::getPublicKey method.

private function getPublicKey(string $pem)
{
    $publicKey = openssl_pkey_get_public($pem);
    $this->validateKey($publicKey);
    return $publicKey;
}

In the getPublicKey method, the openssl_pkey_get_public method is given a private key, shouldn't this method be given a publicKey?
image


So when I looked at the docs (with the above $config->signingKey() on its own) I got the following error when validating the token

{
   "name":"Exception",
   "message":"It was not possible to parse your key, reason:\n* error:0480006C:PEM routines::no start line\n* error:0480006C:PEM routines::no start line\n* error:0480006C:PEM routines::no start line\n* error:0480006C:PEM routines::no start line\n* error:0480006C:PEM routines::no start line\n* error:0480006C:PEM routines::no start line",
   "code":0,
   "type":"Lcobucci\\JWT\\Signer\\InvalidKeyProvided",
   "file":"/var/www/vendor/lcobucci/jwt/src/Signer/InvalidKeyProvided.php",
   "line":13,
   "stack-trace":[
      "#0 /var/www/vendor/lcobucci/jwt/src/Signer/OpenSSL.php(109): Lcobucci\\JWT\\Signer\\InvalidKeyProvided::cannotBeParsed()",
      "#1 /var/www/vendor/lcobucci/jwt/src/Signer/OpenSSL.php(95): Lcobucci\\JWT\\Signer\\OpenSSL->validateKey()",
      "#2 /var/www/vendor/lcobucci/jwt/src/Signer/OpenSSL.php(80): Lcobucci\\JWT\\Signer\\OpenSSL->getPublicKey()",
      "#3 /var/www/vendor/lcobucci/jwt/src/Signer/Ecdsa.php(38): Lcobucci\\JWT\\Signer\\OpenSSL->verifySignature()",
      "#4 /var/www/vendor/lcobucci/jwt/src/Validation/Constraint/SignedWith.php(32): Lcobucci\\JWT\\Signer\\Ecdsa->verify()",
      "#5 /var/www/vendor/lcobucci/jwt/src/Validation/Validator.php(48): Lcobucci\\JWT\\Validation\\Constraint\\SignedWith->assert()",
      "#6 /var/www/vendor/bizley/jwt/src/Jwt.php(313): Lcobucci\\JWT\\Validation\\Validator->validate()",
      "#7 /var/www/vendor/bizley/jwt/src/JwtHttpBearerAuth.php(158): bizley\\jwt\\Jwt->validate()",
      "#8 /var/www/vendor/bizley/jwt/src/JwtHttpBearerAuth.php(125): bizley\\jwt\\JwtHttpBearerAuth->processToken()",
      "#9 /var/www/vendor/yiisoft/yii2/filters/auth/AuthMethod.php(59): bizley\\jwt\\JwtHttpBearerAuth->authenticate()",
      "#10 /var/www/vendor/yiisoft/yii2/base/ActionFilter.php(77): yii\\filters\\auth\\AuthMethod->beforeAction()",
      "#11 [internal function]: yii\\base\\ActionFilter->beforeFilter()",
      "#12 /var/www/vendor/yiisoft/yii2/base/Component.php(633): call_user_func()",
      "#13 /var/www/vendor/yiisoft/yii2/base/Controller.php(297): yii\\base\\Component->trigger()",
      "#14 /var/www/vendor/yiisoft/yii2/web/Controller.php(218): yii\\base\\Controller->beforeAction()",
      "#15 /var/www/vendor/yiisoft/yii2/base/Controller.php(176): yii\\web\\Controller->beforeAction()",
      "#16 /var/www/vendor/yiisoft/yii2/base/Module.php(552): yii\\base\\Controller->runAction()",
      "#17 /var/www/vendor/yiisoft/yii2/web/Application.php(103): yii\\base\\Module->runAction()",
      "#18 /var/www/vendor/yiisoft/yii2/base/Application.php(384): yii\\web\\Application->handleRequest()",
      "#19 /var/www/backend/web/index.php(18): yii\\base\\Application->run()",
      "#20 {main}"
   ],
   "success":false
}

I then (after a lot of searching :D) ,
image
from this

I switched to this
image

and the error went away


Sorry my english :) (sorry from google translate xD)

Token always unauthorized

In my main.php

'components' => [
        'jwt' => [
            'class' => \bizley\jwt\Jwt::class,
            'signer' => \bizley\jwt\Jwt::HS256,
            'signingKey' => 'c53d6ef5c936ead69b750eb7e20dd1341b18b1508ee399b8e532b1f42f2b95ca', 
            'verifyingKey' => 'c53d6ef5c936ead69b750eb7e20dd1341b18b1508ee399b8e532b1f42f2b95ca', 
            'validationConstraints' => static function (\bizley\jwt\Jwt $jwt) {
                $config = $jwt->getConfiguration();
                return [
                    new \Lcobucci\JWT\Validation\Constraint\SignedWith($config->signer(), $config->verificationKey()),
                    new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
                        new \Lcobucci\Clock\SystemClock(new \DateTimeZone(\Yii::$app->timeZone)),
                        new \DateInterval('PT10S')
                    ),
                ];
            }
        ],
]

in my user.php

 public static function findIdentityByAccessToken($token, $type = null)
    {   
        $claims = \Yii::$app->jwt->parse($token)->claims();
        $uid = $claims->get('uid');
        if (!is_numeric($uid)) {
            throw new ForbiddenHttpException('Invalid token provided');
        }

        return static::findOne(['id' => $uid]);
    }

and in my user controller for login

public function actionLogin() 
    {
        $request = Yii::$app->request;

        $nric = $request->post('nric');
        $pin = $request->post('pin');

        if(empty($nric) || empty($pin)) 
        {
            return [
                'status' => 'Error',
                'message' => 'Nric and pin are required',
            ];
        }

        // Find the user by nric 
        $user = Parish::findByNric($nric);

        if($user && $user->validatePin($pin)) {

    
            $now = new \DateTimeImmutable('now', new \DateTimeZone(\Yii::$app->timeZone));

            $token = Yii::$app->jwt->getBuilder()
                -> issuedBy('MasjidPro')
                -> permittedFor('MasjidPro App')
                -> issuedAt($now)
                -> canOnlyBeUsedAfter($now)
                -> expiresAt($now->modify('+1 hour'))
                -> withClaim('uid', $user->id)
                -> getToken(
                    \Yii::$app->jwt->getConfiguration()->signer(),
                    \Yii::$app->jwt->getConfiguration()->signingKey()
                );
                // -> identifiedBy('4f1g23a12aa')
                // -> withHeader('foo', 'bar')
                
            return [
                'status' => 'Success',
                'user' => [
                    'name' => $user->name,
                    'nric' => $user->nric,
                ],
                'token' => $token->toString(),
                'now' => $now
            ];
        } else {
            return [
                'status' => 'Error',
                'message' => 'Invalid credentials',
            ];
        }
    }

however everytime i tried to use the token, it is unauthorized. Is there anything i left out?

Screenshot_7

Token isn't expiring

Hello, I have my token setup and all seems working, except they don't expire. Here is how I'm creating the token:

$token = \Yii::$app->jwt->getBuilder()
			->identifiedBy('45f1g23a12aa', true) 
			->issuedBy('https://mysite.com')
			->issuedAt($now)
			->canOnlyBeUsedAfter($now)
			->expiresAt($now->modify('+20 hour')) 
			->withClaim('uid', $userId)
			->getToken(
				\Yii::$app->jwt->getConfiguration()->signer(),
				\Yii::$app->jwt->getConfiguration()->signingKey()
			);

Here is my config.php

        'jwt' => [
            'class' => 'bizley\jwt\Jwt',
            'signer' => \bizley\jwt\Jwt::HS256,
            'signingKey' => "mysecret",
            'verifyingKey' => "mysecret",
            'validationConstraints' => function (\bizley\jwt\Jwt $jwt) {
                $signer = $jwt->getConfiguration()->signer();
                $pubKey = $jwt->getConfiguration()->signingKey();
                return [
                    new \Lcobucci\JWT\Validation\Constraint\SignedWith($signer, $pubKey),
                ];
            },
        ],

Was there something else I needed to do to make Yii2 honor the token expiration? I've used the debug tool at https://jwt.io and it says the jwt token is valid so I'm out of ideas. Thanks for any help!

the problem is about select user model

Hi I use your package and I have a problem

assume I have two

'user' => [ 'identityClass' => 'app\models\User', ], 'admin' => [ 'class' => 'yii\web\User', 'identityClass' => 'app\models\Admin', ],

when I want to authenticate by jwt, it seems we have two request one for user and another one for admin

I don't need admin one, when I remove admin part from web.php the problem resolves

it seems it can't detect which user model it should use in AccessControll we define :

             'user' => Yii::$app->admin, 

but here we don't have anyone

sizeg/yii2-jwt to bizley/yii2-jwt fails to validate \Lcobucci\JWT\Validation\Constraint\SignedWith constraint

We previously used sizeg/yii2-jwt package to manage JWT. Parsing and validation was working fine. During migration to PHP 8.1 we encountered compatibility issues and decided to switched to bizley/yii2-jwt.

Following new package instructions we reconfigured application to match 1 to 1 configuration-wise. Token generation works as expected, however \Lcobucci\JWT\Validation\Constraint\SignedWith always produces Token signature mismatch exception, which seems to be hash mismatch (found out during debugging). The secret passed properly, I've double checked that. However there is still mismatch.

Just to give you more insight. We have client application on React, users store JWT via Cookies/LocalStorage. Some of the generated JWT using sizeg/yii2-jwt (old package) and when new package is using \Lcobucci\JWT\Validation\Constraint\SignedWith constraint - validation fails. Here is specific place where it fails - (https://github.com/lcobucci/jwt/blob/5.0.x/src/Validation/Constraint/SignedWith.php#L28-L30).

In the old configuration as well in new we used: HS256 (Sha256).

Old configuration variant looks like this:

 'jwt' => [
    'class' => '\sizeg\jwt\Jwt',
    'key' => 'secret-key' // HS256 (Sha256) by default
],

New variant looks as following:

'jwt' => [
    'class' => \bizley\jwt\Jwt::class,
    'signer' => \bizley\jwt\Jwt::HS256,
    'signingKey' => [
        'key' => 'secret-key',
        'store' => \bizley\jwt\Jwt::STORE_IN_MEMORY,
        'method' => \bizley\jwt\Jwt::METHOD_PLAIN,
        'passphrase' => '',
    ],
    'validationConstraints' => static function (\bizley\jwt\Jwt $jwt) {
        $config = $jwt->getConfiguration();
        return [
            new \Lcobucci\JWT\Validation\Constraint\SignedWith($config->signer(), $config->signingKey()),
        ];
    }
],

Could you please give a hint why this may happen?

[Q] How to use this lib "validation-only"?

We used to use the sizeg lib "validation-only", so actually there's no need for a signer and private key, right?

But configuring a proper signer algorithm is required, and if it's asymetric, you need a key file etc...
So our current workaround is to pass the public key to the signer config, which actually makes no sense.

How do we need to configure the lib to use it only for validation ie. without specifying any private key.

Related discussions:

CC: @amk0 @eluhr @handcode

Tokens sometimes give odd error on pages that auto-refresh

Hello, my tokens are working - with one exception. The token's work and expire unless you leave our webapp open to a page that auto-refreshes (a normal page just logs the user out. Thank you for any help, I appreciate it!

We are using the Yii2 framework as a microservice framework with the controllers using this in the behaviors section:

			'authenticator' => [
				'class' => JwtHttpBearerAuth::class,
			],

Those users end up with this error:

Lcobucci\JWT\Token\InvalidTokenStructure: The JWT string must have two dots in /var/www/html/ciims/api/vendor/lcobucci/jwt/src/Token/InvalidTokenStructure.php:13Stack trace:#0 /var/www/html/ciims/api/vendor/lcobucci/jwt/src/Token/Parser.php(54): Lcobucci\JWT\Token\InvalidTokenStructure::missingOrNotEnoughSeparators()#1 /var/www/html/ciims/api/vendor/lcobucci/jwt/src/Token/Parser.php(31): Lcobucci\JWT\Token\Parser->splitJwt()#2 /var/www/html/ciims/api/vendor/bizley/jwt/src/Jwt.php(281): Lcobucci\JWT\Token\Parser->parse()#3 /var/www/html/ciims/api/vendor/bizley/jwt/src/JwtHttpBearerAuth.php(156): bizley\jwt\Jwt->parse()#4 /var/www/html/ciims/api/vendor/bizley/jwt/src/JwtHttpBearerAuth.php(125): bizley\jwt\JwtHttpBearerAuth->processToken()#5 /var/www/html/ciims/api/vendor/yiisoft/yii2/filters/auth/AuthMethod.php(59): bizley\jwt\JwtHttpBearerAuth->authenticate()#6 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/ActionFilter.php(77): yii\filters\auth\AuthMethod->beforeAction()#7 [internal function]: yii\base\ActionFilter->beforeFilter()#8 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/Component.php(633): call_user_func()#9 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/Controller.php(297): yii\base\Component->trigger()#10 /var/www/html/ciims/api/vendor/yiisoft/yii2/web/Controller.php(218): yii\base\Controller->beforeAction()#11 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/Controller.php(176): yii\web\Controller->beforeAction()#12 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/Module.php(552): yii\base\Controller->runAction()#13 /var/www/html/ciims/api/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction()#14 /var/www/html/ciims/api/vendor/yiisoft/yii2/base/Application.php(384): yii\web\Application->handleRequest()#15 /var/www/html/ciims/api/index.php(42): yii\base\Application->run()#16 {main}

Here is the token:

$token = \Yii::$app->jwt->getBuilder()
			->identifiedBy('45f1g23a12aa', true) 
			->issuedBy('https://mysite.com')
			->issuedAt($now)
			->canOnlyBeUsedAfter($now)
			->expiresAt($now->modify('+20 hour')) 
			->withClaim('uid', $userId)
			->getToken(
				\Yii::$app->jwt->getConfiguration()->signer(),
				\Yii::$app->jwt->getConfiguration()->signingKey()
			);

Here is my config.php

    'jwt' => [
        'class' => bizley\jwt\Jwt::class,
        'signer' => \bizley\jwt\Jwt::HS256,
        'signingKey' => base64_decode("reallylongkeyhere"),
        'verifyingKey' => base64_decode("reallylongkeyhere"),
        'validationConstraints' => function (\bizley\jwt\Jwt $jwt) {
            $signer = $jwt->getConfiguration()->signer();
            $pubKey = $jwt->getConfiguration()->signingKey();
            return [
                new \Lcobucci\JWT\Validation\Constraint\SignedWith($signer, $pubKey),
                new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
                    new \Lcobucci\Clock\SystemClock(new \DateTimeZone(\Yii::$app->timeZone)),
                    new \DateInterval('PT10S')
                ),
            ];
        },
    ],

No constraint given

Describe the bug
No constraint given.
/vendor/bizley/jwt/src/JwtHttpBearerAuth.php:119

My config

'jwt' => [
            'class' => Jwt::class,
            'signer' => Jwt::HS256,
            'signingKey' => 'hy2#Y3hk4*3j3lf83FJFKmbr%$d3',
        ]

Controller

public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => JwtHttpBearerAuth::class,
            'except' => [
                'options'
            ],
        ];

        return $behaviors;
    }

i can't understand why i get this error and how to fix it

[Q] How to set validationConstraints?

1 how to set value to validationConstraints? can you give a sample?
2 set the validationConstraints to componensts as this?

'jwt' => [
'class' => bizley\jwt\Jwt::class,
'signer' => bizley\jwt\Jwt::RS256,
'signingKey' => '',
'verifyingKey' => [
'key' => @'pubkey.pem', /* key content /
'passphrase' => '', /
key passphrase /
'store' => bizley\jwt\Jwt::STORE_IN_MEMORY, /
storage type /
'method' => bizley\jwt\Jwt::METHOD_FILE /
method type */
],
'validationConstraints'=> [
**************************
]
],

Improvements ideas

Setting up lcobucci/jwt / bizley/yii2-jwt was a painful process for me:

  1. Errors were silent or not clear; I had to debug library code to find configuration issues.
  2. There are no constraints (validators) configured out-of-the box ๐Ÿ˜ฟ.

However I finally managed to make it work, so I am sharing code with you guys:

// component configuration
[
    'class' => \bizley\jwt\Jwt::class,
    'signer' => \bizley\jwt\Jwt::RS256,
    'signingKey' => base64_decode("LS0tLS1CRUdJTiBSU0EgUF....."),
    'verifyingKey' => base64_decode("LS0tLS1CRUdJTiBQVUJMS....."),
    'validationConstraints' => function(\bizley\jwt\Jwt $jwt) {
        $signer = $jwt->getConfiguration()->signer();
        $pubKey = $jwt->getConfiguration()->verificationKey();
        $clock = \Lcobucci\Clock\FrozenClock::fromUTC();
        $clock->setTo(new \DateTimeImmutable());
        return [
            new \Lcobucci\JWT\Validation\Constraint\SignedWith($signer, $pubKey),
            new \Lcobucci\JWT\Validation\Constraint\ValidAt($clock),
        ];
    },
]

Originally posted by @koxu1996 in #14 (comment)

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.