Lravel 5.4: JWT API with multi-auth on two tables one works the other not

北城余情 提交于 2019-11-30 10:47:21

There is no need to change the providers in config/auth.php.

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

DriverController

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

My example when i used multi auth with jwt

I have 2 models : 1. users 2. admins

the routes :

Route::post('auth/userlogin', 'ApiController@userLogin');
Route::post('auth/adminlogin', 'ApiController@adminLogin');

the controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Config;
use JWTAuth;
use JWTAuthException;
use App\User;
use App\Admin;

class ApiController extends Controller
{

    public function __construct()
    {
        $this->user = new User;
        $this->admin = new Admin;
    }

    public function userLogin(Request $request){
        Config::set('jwt.user', 'App\User'); 
        Config::set('auth.providers.users.model', \App\User::class);
        $credentials = $request->only('email', 'password');
        $token = null;
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    'response' => 'error',
                    'message' => 'invalid_email_or_password',
                ]);
            }
        } catch (JWTAuthException $e) {
            return response()->json([
                'response' => 'error',
                'message' => 'failed_to_create_token',
            ]);
        }
        return response()->json([
            'response' => 'success',
            'result' => [
                'token' => $token,
                'message' => 'I am front user',
            ],
        ]);
    }

    public function adminLogin(Request $request){
        Config::set('jwt.user', 'App\Admin'); 
        Config::set('auth.providers.users.model', \App\Admin::class);
        $credentials = $request->only('email', 'password');
        $token = null;
        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json([
                    'response' => 'error',
                    'message' => 'invalid_email_or_password',
                ]);
            }
        } catch (JWTAuthException $e) {
            return response()->json([
                'response' => 'error',
                'message' => 'failed_to_create_token',
            ]);
        }
        return response()->json([
            'response' => 'success',
            'result' => [
                'token' => $token,
                'message' => 'I am Admin user',
            ],
        ]);
    }
}

I hope that's help you .

First let me thank you @AmrAbdelRahman for you efforts and your time.

My problem was the application always using my default authentication "guard" as my default looks like that

'defaults' => [
        'guard'     => 'api',
        'passwords' => 'users',
    ],

so every time I try to authenticate the other user which was the driver it fails during the default authenticate is api and the it should using driver in this case.

what I did in my case was making a switcher in my App\Providers\AppServiceProvider under the boot here is how it looks like

$this->app['router']->matched(function (\Illuminate\Routing\Events\RouteMatched $e) {
            $route = $e->route;
            if (!array_has($route->getAction(), 'guard')) {
                return;
            }
            $routeGuard = array_get($route->getAction(), 'guard');
            $this->app['auth']->resolveUsersUsing(function ($guard = null) use ($routeGuard) {
                return $this->app['auth']->guard($routeGuard)->user();
            });
            $this->app['auth']->setDefaultDriver($routeGuard);
        });

Now in my case if the $guard =api it will read that guard and act correctly and if it's driver it will use the new guard and act as expected. Hope this will help some one in future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!