Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jwt with multiple model

I use Lavarel 5.2 framework with jwt for authorization
jwt takes user info form token just with one model, now how can i parse user token with jwt on multiple model?
For sample when i use customer token in a api jwt parse that token from customer model , default guard should be customer
auth.php :

'defaults' => [
    'guard' => 'operator',
    'passwords' => 'operators',
],

'guards' => [
    'operator' => [
        'driver' => 'session',
        'provider' => 'operators',
    ],
    'customer' => [
        'driver' => 'session',
        'provider' => 'customers',
    ],
    'biker' => [
        'driver' => 'session',
        'provider' => 'bikers',
    ]
],

'providers' => [
    'operators' => [
        'driver' => 'eloquent',
        'model' => App\Http\Services\Auth\Model\User::class,
    ],
    'customers' => [
        'driver' => 'eloquent',
        'model' => App\Http\Aggregate\Customer\Model\Customer::class,
    ],
    'bikers' => [
        'driver' => 'eloquent',
        'model' => App\Http\Aggregate\Biker\Model\Biker::class,
    ]
],
like image 865
bitcodr Avatar asked Sep 07 '16 07:09

bitcodr


2 Answers

You can create a separate middleware like AuthModel. In that you can set the config to take which providers like the below,

Config::set('auth.providers.users.model',\App\Models\Customer::class);

If you want to use multiple models, then need to use if conditions to check which url can access which models. It can be like,

if(url == '/customer/api/') {
 Config::set('auth.providers.users.model',\App\Models\Customer::class);
} else if(url == '/biker/api/') {
 Config::set('auth.providers.users.model',\App\Models\Biker::class);
}

In the above example, I have used url just for example, so get it from the request.

like image 110
suguna Avatar answered Oct 15 '22 06:10

suguna


You can change the __construct function in each of your controllers as follows. So that jwt know which model to authenticate.

BikerController

function __construct()
{
    Config::set('jwt.user', Biker::class);
    Config::set('auth.providers', ['users' => [
            'driver' => 'eloquent',
            'model' => Biker::class,
        ]]);
}

CustomerController

function __construct()
{
    Config::set('jwt.user', Customer::class);
    Config::set('auth.providers', ['users' => [
            'driver' => 'eloquent',
            'model' => Customer::class,
        ]]);
}
like image 28
shavindip Avatar answered Oct 15 '22 06:10

shavindip