Luciasar
Luciasar

Reputation: 393

Laravel 5.2 Multi-Auth with API guard uses wrong table

I'm trying to get a multi-auth system working where Users can log in via the normal web portal, but a separate database of entities (named "robots" for example) can also log in via an API guard token driver. But no matter what I do, the setup I have is not directing my authentication guard to the correct Robot database and keeps trying to authenticate these requests as Users via tokens (which fails, because users don't have tokens).

Can someone help me find where I've gone wrong?

I've started by putting together a middleware group in Kernel.php:

'api' => [
    'throttle:60,1',
        'auth:api',
],

This uses settings in config/auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'robots',
        ],
    ],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'robots' => [
        'driver' => 'eloquent',
        'model' => App\Models\Robot::class,
    ],
],

The middleware gets called in routes.php

Route::group(['middleware' => 'api'], function () {
    Route::get('api/request', 'API\RequestController@index');
});

It uses this model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;

class Robots extends Authenticatable
{
    protected $fillable = [
        'serial_number','api_token',
    ];
    protected $guard = 'Robots';

    protected $hidden = [
        'api_token',
    ];
}

Any ideas?

Update: on further inspection, it appears that most of the settings in auth.php are not applying properly - is there some way I can force these settings to take effect?

Upvotes: 13

Views: 2807

Answers (2)

Luciasar
Luciasar

Reputation: 393

Actual issue/solution:

Laravel has a separate, rarely mentioned cache that exists exclusively for its config files. Normal cache and class reset methods like composer dump-autoload and php artisan cache:clear do not affect this cache, which was leading to my confusing state of having none of the settings in my auth.php file take effect.

The correct way to clear this cache is to use the commands:

php artisan config:cache

php artisan config:clear

These resolved my issue.

Upvotes: 4

henrik
henrik

Reputation: 1618

In your config/auth.php you specify the provided model to be used for robots provider: 'model' => App\Models\Robot::class However your Robot class is defined as class Robots extends Authenticatable, which is a mismatch of the class name.

Rename your class to class Robot

Upvotes: 3

Related Questions