Как использовать другую охрану при входе из сети или API в Laravel?

Я создаю приложение Laravel (5.7) для мобильного приложения. Итак, у меня есть API и веб-панель, оба должны войти в систему, и у каждого есть модель. Для входа в Интернет я использую User модель (так как это оперативные роли) и другая модель Client для пользователей, зарегистрированных через приложение.

я использую JWT создавать токены авторизации для мобильного приложения и использовать обычный вход в систему для веб-панели.

Сложность в том, что по умолчанию auth.php guard является web и если я использую (следующий) метод аутентификации из API, он переходит к таблице пользователей, а не к таблице клиентов, и исправляется, когда я изменяю защиту по умолчанию на api, но веб-вход в систему затем пытается найти в clients таблица

Итак, короче говоря, я попытался переключить охрану по умолчанию разными способами, но это просто не сработает. Вот некоторые из тестов (которые не прошли):

  • Изменение переменной $guard в контроллере входа на web и установка api по умолчанию в auth.php
  • Перезаписывает значения по умолчанию auth.php guard во время выполнения, используя Config::set('auth.defaults.guard' , 'api'); или же config('auth.defaults.guard' , 'api'); (и все его варианты) в методе проверки подлинности моего API

Это мой файл auth.php

<?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,
        ],
    ],

];

Мой метод аутентификации в моем 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'));
    }

Кроме того, вот моя модель клиента

<?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 [];
    }

}

1 ответ

$request Экземпляр имеет user метод, который принимает один аргумент:

$request->user('apiguard');

Если вы пытаетесь аутентификации:

Auth::guard('apiguard')->attempt($credentials);
Другие вопросы по тегам