Laravel 5.2 Multi-Auth with API guard

Posted 3 years ago by lcopeland

Hi all. 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 called Robots can also log in via an API guard style token driver. I'm very excited about how easy 5.2 is supposed to make this but I can't seem to get it working - no matter what I do, the setup I have is not directing my auth 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\[email protected]');
});

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',
    ];

Quite the web of files, and I'm lost. Any ideas? }

Please sign in or create an account to participate in this conversation.