简体   繁体   中英

How to use different guard when login in from web or api in Laravel?

I am creating a Laravel (5.7) application for a mobile app. So I have an API and a Web Panel, both need to log in and each have a model. For Web login I use the User model (since this are operative roles) and another model Client for the users registered through the app.

I am using JWT to create auth tokens for the mobile app and using the regular login for the Web Panel.

The complication is that the default auth.php guard is web and if I use the (following) authenticate method from the API it goes to look to the users table, instead of the clients table, and its fixed when I change de default guard to api but the Web login then tries to look in the clients table .

So, in short I've tried to switch this default guards in many different ways but it just won't work. Some of the tests (that failed) I did are:

  • Changing the $guard variable in the login controller to web and setting api as default in auth.php
  • Overwriting the defaults auth.php guard in execution time using Config::set('auth.defaults.guard' , 'api'); or config('auth.defaults.guard' , 'api'); (and all its variations) in my API's authenticate method

This is my auth.php file

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

        'api' => [
            'driver' => 'session',
            'provider' => 'clients'
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

         'clients' => [
             'driver' => 'eloquent',
             'model' => App\Client::class,
         ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

My authenticate method in my ApiClientController.php

 public function authenticate(Request $request)
    {
//        config('auth.defaults.guard' , 'api'); // NOT WORKING!!
//        Config::set('auth.guards.web.provider', 'clients'); // NOT WORKING!!
//        Config::set('auth.providers.users.model', Client::class); // NOT WORKING!!
//        config('auth.providers.users.model', Client::class); // NOT WORKING!!

        $credentials = $request->only('phone', 'password');

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 400);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        Log::info("JWT Token: $token");

        return response()->json(compact('token'));
    }

Also, here is my Client model

<?php

namespace App;


use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Client extends Authenticatable implements JWTSubject
{

    protected $hidden = [
        'password', 'phone_verification_code', 'phone_verified_at'
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }

}

The $request instance has a user method that takes one argument:

$request->user('apiguard');

If you are attempting authentication:

Auth::guard('apiguard')->attempt($credentials);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM