tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.23k stars 1.55k forks source link

Can I provide a custom name for the key? #1999

Open yashaswini opened 4 years ago

yashaswini commented 4 years ago

Subject of the issue

I wanted to know if we can use a custom name for the key. By default it takes it as token which is defined in KeyTrait.

Your environment

Q A
Bug? no
New Feature? no
Framework Laravel
Framework version 7
Package version 1.0
PHP version 7

Steps to reproduce

Since I wanted to use a custom name for the key, when I implement this package after authentication it returns null while I attempt to authorise a valid user since the key name I use to what is defined in package is different.

Expected behaviour

Should be able to set a custom name to key

Actual behaviour

I am able to retrieve valid results only when I match my key name to "token"

mitchglenn commented 3 years ago

I haven't tested this, but here's an idea.

The key called "token" is used in the chain of Parsers. You can create your own provider to extend (override) the default parser. Within your own parser, you can use the setKey() method to change the name of the key from "token" to whatever you want.

Here's an example

Create your own JWTParserProvider.php file and inside of the register() method extend the parser provided by this library.

$this->app->extend('tymon.jwt.parser', function ($app) {
            $queryString = (new QueryString())->setKey('my_jwt_token');

            $parser = new Parser(
                $app['request'],
                [
                    new AuthHeaders,
                    $queryString,
                    new InputSource,
                    new RouteParams,
                    new Cookies($this->config('decrypt_cookies')),
                ]
            );

            $app->refresh('request', $parser, 'setRequest');

            return $parser;
});

In the above example, I'm only overriding the name of the key for the QueryString parser, but you could apply the same override to the other classes in the chain that use the key.

Hope that helps!

Stuffa1991 commented 3 years ago

You can look at this pull request https://github.com/tymondesigns/jwt-auth/pull/1933

stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

rechik commented 7 months ago

Place in any service provider

public function register(): void
{
    $this->app['tymon.jwt.parser']->addParser([
        (new Cookies(config('jwt.decrypt_cookies')))->setKey('jwt'),
    ]);
}