i'm reading in Authentication section in laravel website https://laravel.com/docs/5.2/authentication
can anyone explain how I can do this , like the documentation explains , to specify separate tables for authentication ... i will quotes from laravel like below :
Accessing Specific Guard Instances
You may specify which guard instance you would like to utilize using
the guard method on the Auth facade. This allows you to manage
authentication for separate parts of your application using entirely
separate authenticatable models or user tables.
The guard name passed to the guard method should correspond to one of
the guards configured in your auth.php configuration file:
if (Auth::guard('admin')->attempt($credentials)) {
//
}
You kinda have to read the examples of adding custom guards and providers, the configuration part of it mainly. You can use the same auth 'driver', you just want to adjust what model is used by the Auth user provider.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
// add another one
// use the same driver, 'session', but a different user provider
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// add a provider using Eloquent but using a different model
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
]
Then you should be able to specify the guard admin to Auth. As long as that Admin model implements Authenticatable and you are passing the appropriate credentials to attempt on Auth you should be good.
If you have more middlewares and you want to apply more than one guard and by this i mean middleware you can do this in any Middleware.php file:
public function handle($request, Closure $next)
{
// if a user is Agency or Admin, let him through
if (Auth::user()->isAgency() || Auth::user()->isAdmin()) {
return $next($request);
}
// else show error page
abort(403);
}
Related
I am trying to use the standard Laravel auth related functionality. I have the standard login, register, logout, etc... working fine. But my problem is that whenever I go to use functions like Auth::user() this is returning the GenericUser model rather than my own App/Models/User.php model. The problem is that my User's model has some foreign key references to other data so I would like to work exclusively with my User model.
For example, when trying to make a Policy I am running into an error:
Argument 1 passed to App\Policies\ContractPolicy::before() must be an
instance of App\Models\User, instance of Illuminate\Auth\GenericUser
given
And the code simply looks like this:
<?php
namespace App\Policies;
use App\Models\Contract;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class ContractPolicy
{
use HandlesAuthorization;
public function before(User $user, $ability)
{
if ($user->isSuperAdmin()) {
return true;
}
}
public function viewAny(User $user)
{
return $user->isMember();
}
}
The GenericUser model is indeed returning the data from the users table, but the problem is that it is completely different from what my User model gives, and thus includes nothing like the foreign key references or functions I added. I was under the impression that I could switch the model used by switching the config/auth.php provider. Which I did and nothing seemed to change:
'providers' => [
'users' => [
'model' => App\Models\User::class,
],
'users' => [
'driver' => 'database',
'table' => 'users',
],
],
What am I doing wrong here?
You are defining the users provider to use the 'database' driver:
'users' => [
'driver' => 'database',
'table' => 'users',
],
Adjust that to use the 'eloquent' driver instead:
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
The 'database' driver uses Query Builder to interact with the database table and returns an object of GenericUser to represent the currently authenticated user.
The 'eloquent' driver uses an Eloquent Model to interact with the database and returns a Model instance. If you like relationships and all the other features of Eloquent then you should stick with using the 'eloquent' driver. Also, you have defined your Policy methods to be expecting a particular Model passed to its methods.
I followed the instructions to setup and install Laravel Breeze and it worked to the extent that I could register a user and subsequently log in, so that's cool.
What I'm struggling to get working is to set up my API routes to only be accessible when a user is logged in.
In my api.php file, I have this route set up to return ["message" => "success"] which I can access at /api/test if I remove the middleware wrapper. I have tried putting in various things in the below middleware bit - ['auth'], ['auth.api'] etc but nothing seems to work. Some middleware 'passes' but inside my TestController, if I dump Auth::user(), I get null.
Route::middleware( ?? what goes here ??)->group(function () {
Route::get('test', TestController::class);
});
This is my guards file, I copied the API section from stackO.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
'hash' => false,
],
],
Any assistance would be welcomed, thank you
I'm working on a small project using Laravel / VueJS, I'm using Passport for Authentication.
I have three pages: Login, Register, HomeController
My Question is since now I'm using Passport to login ( Token ), which middleware I should use for HomeController? I tried to use:
public function __construct()
{
$this->middleware('auth:api');
}
but it didn't work since I'm sending the Bearer token using Postman just for test.
HomeController contains a static view with no dynamic data, but I want to protect it, so that only logged users can see it.
in your application's config/auth.php configuration file the driver should be set to passport :
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
reference: https://laravel.com/docs/8.x/passport#installation
as for the middleware, it stays the same : auth:api
I have a problem that I'm facing with Laravel 6 LTS version. I have 3 different controllers: AdminController (/admin), ScheduleController (/schedule) and ClientController (/client). Each of those controller should authenticate different database table of users. For /admin it uses 'users' table, for /schedule it uses 'companies' table and for /client it uses 'clients' table. Technically, you should be able to login to each "controller" without the worry of colliding with other controllers. For instance, you can be logged in to /admin and also to /client and /schedule (separate login form for each). How should I go about this? Can someone point me in the right direction? Is this possible with Laravel?
Thanks
You can set different user providers in config/auth.php
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
Reference
Just can't get the Lumen authentication to work at all.
I have a fresh install and trying to follow the docs here:
https://lumen.laravel.com/docs/5.2/authentication
I've Uncommented the AuthProvider line in the app.php file (along with everything else, facade, etc). Then in a simple controller I just do dd(Auth::use()).
I just can't get around this error:
Undefined index: provider
in AuthManager.php line 152
at Application->Laravel\Lumen\Concerns\{closure}('8', 'Undefined index: provider', '/home/vagrant/Code/gryd/api.gryd.com/vendor/illuminate/auth/AuthManager.php', '152', array('name' => 'api', 'config' => array('driver' => 'token'))) in AuthManager.php line 152
Any ideas?
EDIT:
Since someone asked for a code sample.
Install Lumen
Uncomment everything in app.php
Put this in routes:
$app->get('/api/v1/users/{id}', function () {
dd(\Auth::user());
});
This is what I've got so far, which is working but not quite how I'd like it. The following works for Token-based auth, which is the default setting in Lumen.
Enable Authentication
Register routeMiddleware and AuthServiceProvider by un-commenting the following lines in bootstrap/app.php.
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
and
$app->register(App\Providers\AuthServiceProvider::class);
Configuration
Copy vendor/laravel/lumen-framework/config/auth.php to config/auth.php. Create the root config folder if you have to.
Inside we will find four items (defaults, guards, providers, passwords). We're concerned with the first three.
First we name the default guard as ABC.
'defaults' => [
'guard' => env('AUTH_GUARD', 'ABC'),
],
Next we define the ABC guard with token as its driver and XYZ as its provider.
'guards' => [
'ABC' => [
'driver' => 'token',
'provider' => 'XYZ'
],
],
And the XYZ provider is defined with eloquent as the driver and App\User::class as the model.
'providers' => [
'XYZ' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Completing Setup
Finally, we use the auth middleware in our routing setup, as usual.
$app->group(['middleware' => 'auth'], function () use ($app) {
So this is what gets the token auth up and running. It uses the api_token field in the users table to authenticate, which can be found in TokenGuard.
I still haven't found out what effect AuthServiceProvider and $this->app['auth']->viaRequest('api', function ($request) { have on my app yet.
Well I still haven't found out how to change the api request type via .env. But for now switching it to token seems to work.
Changed Auth::viaRequest('api', functi to Auth::viaRequest('token', funct.