Change default auth guard name in Laravel - php

The default auth guard name in Laravel is 'web', but I found this confusing as it's provider is 'users'. Especially because for the admin guard the name is admin and the provider is admins (I'm using this for Nova). I'm on Laravel 6.5.2.
So I wanted to change this. In my config/auth I have:
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
and
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
and
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
In App\Models\User I have
protected $guard = 'user';
In App\Http\Controllers\Auth\LoginController I have
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:user')->except('logout');
$this->middleware('guest:admin')->except('logout');
}
Now I get the error Auth guard [web] is not defined when logging in. Is it a bad idea to change it from web to user?
I found setting up the guards quite confusing, because you can define things in:
config/auth
In the model (protected $guard = 'guard_name';)
In the LoginController, RegisterController and ResetPasswordController as per the Laravel docs (protected function guard() { return Auth::guard('guard-name');})
In this article it's described that it's possible to do what I'm trying to achieve.

I think that happens because in the default app/Providers/Route service provider.php class, there is this method that registers your roites/web.php file with the web middleware. You should change the middleware name here as well:
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}

If you're using sanctum, make sure to add
'guard' => 'user',
to your sanctum.php config file.
You'll then need to run php artisan config:cache

Change app/Providers/RouteServiceProvider.php
protected $namespaceUser = 'App\Http\Controllers\User';
public function boot()
{
...
$this->routes(function () {
Route::middleware('user')
->namespace($this->namespaceUser)
->group(base_path('routes/web.php'));
...
});
}
Redefine guard() function on LoginController.php
protected function guard()
{
return Auth::guard('user');
}

Related

Laravel Auth guard [api] is not defined

Laravel 8.83.19
Passport 10.4
Simply started a new project and installed passport and want to use middleware for a route but give this error:
Auth guard [api] is not defined
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
AuthServiceProvider.php
public function boot()
{
Passport::routes();
}
User Model
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
...
User Controller
class UserController extends Controller
{
public function index(Request $request)
{
return User::all();
}
Api.php
Route::middleware('auth:api')->group(function () {
Route::get('/user/index', [UserController::class, 'index']);
});
But when I run http://localhost:8000/api/user/index give me:
InvalidArgumentException: Auth guard [api] is not defined. in file
D:\Workshop\Other\xxx\xxxapi\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
on line 84
ofcourse I cleared cache:
Route::get('/clear', function() {
Artisan::call('cache:clear');
Artisan::call('config:clear');
Artisan::call('config:cache');
Artisan::call('view:clear');
Artisan::call('route:cache');
return "Cleared!";
});
By run this:
http://localhost:8000/clear
Your auth.php file must be like this :
<?php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
]
]
?>
You need to clear config cache to take effect. for Unauthenticated it means token is not valid or is not passed correctly
https://laravel.com/docs/5.7/passport#passing-the-access-token

laravel passport auth:api keeps returns Unauthenticated

I'm using laravel passport and trying to consume the api. After following the docs, everything is good but after a few days, the auth:api keeps returning 'message: "Unauthenticated."' I checked the docs multiple times and couldn't figure out what went wrong. I've also cleared all cache and configs but still the same result. The laravel_token is present in the request header.
Api.php
Route::middleware(['auth:api'])->group(function () {
Route::resource('comment', 'API\CommentController');
Route::resource('notification', 'API\NotificationController');
});
Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
User.php
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable,HasApiTokens;
}
AuthServiceProvider
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
Kernel.php
'web' => [
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, //last
],

Laravel - Getting wrong guard model when I try to use multi authentication

I'm having some problems with Laravel 5.7 multi-auth implementation.
I have created a new table for backend login: "AdminUsers".
So, I modified auth.php file:
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Ecommerce\User::class,
],
'admins' => [
'driver' => 'eloquent',
'table' => Ecommerce\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, I create the AdminLoginController class:
<?php
namespace Ecommerce\Http\Controllers\Admin\Auth;
use Illuminate\Http\Request;
use Ecommerce\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/index';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.auth.login');
}
protected function attemptLogin(Request $request)
{
return $this->guard('admin')->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function authenticated(Request $request, $user)
{
dd('authenticated!');
}
public function username()
{
return 'username';
}
}
I setted this routes in routes file:
Route::get ('/login', ['uses'=>'Auth\AdminLoginController#showLoginForm'])->name('login_page');
Route::post('/login', ['uses'=>'Auth\AdminLoginController#login' ])->name('do_login' );
The problem is, that when I do login, Laravel tries to use "users" guard instead of the defined "admin" guard. So that throw a SQL error (because I have not created the "Users" table in the DB).
Even if I do var_dump($this->guard('admin')) inside AdminLoginController::attemptLogin method, the response gives me a SessionGuard object with "Ecommerce\User" instead of "Ecommerce\AdminUser" that is the one defined as "admin" in auth.php guard array.
Anyone knows where else can I look to solve this?
Thanks!
The problem lies in your auth.php providers section.
'table' => Ecommerce\AdminUser::class
'table' should be replaced with 'model'.

Laravel [5.2.21] Custom Auth Guard not persisting

I'm trying to set up a custom auth guard and everything is mostly working. I'm able to log the Model in, but once I redirect the visitor to a new page the authentication is lost. I can dd() the Auth::guard('client')->user() just fine before the controller does the redirect, but comes up as null in the AuthenticateClient middleware.
I'm using the default guard for authenticating users and everything is working fine with that. I've made sure the routes are under the web middleware which enables sessions.
I've searched for similar issues, but I'm unable to find a solution that works. Any ideas how to fix this?
Side note: I know that I'm using token in the code examples below, but I'm doing more than just validating against that token. So this is a different system than authenticating a token for an api.
Routes:
Route::group(['middleware' => 'web'], function () {
// other routes...
Route::get('client/login/{token}', ['as' => 'client.token', 'uses' => 'Auth\ClientController#attemptTokenLogin']);
Route::group(['prefix' => 'client', 'middleware' => 'auth.client'], function () {
Route::get('dashboard', ['as' => 'client.dashboard', 'uses' => 'ClientController#dashboard']);
});
});
auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
// new auth guard
'client' => [
'driver' => 'session',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// new guard provider
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
],
];
Http/Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
// new...
'auth.client' => \App\Http\Middleware\AuthenticateClient::class,
];
ClientController#attemptTokenLogin
$client = // get the client in a custom way...
Auth::guard('client')->login($client);
// dd(Auth::guard('client')->user()); // this works here
return redirect()->route('client.dashboard');
AuthenticateClient
public function handle($request, Closure $next)
{
// dd(Auth::guard('client')->user()); // this does not work here
if (!Auth::guard('client')->check()) {
return redirect()->route('client.login');
}
return $next($request);
}
When implementing Illuminate\Contracts\Auth\Authenticatable I was not returning getAuthIdentifierName() or getAuthIdentifier()
so...
public function getAuthIdentifierName()
{
$this->getKeyName();
}
public function getAuthIdentifier()
{
$this->getKey();
}
was supposed to be...
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
public function getAuthIdentifier()
{
return $this->getKey();
}

How to use multi Auth in laravel 5.2 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know how to use multi authenticate in laravel 5.2 ! I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?
You need two tables users and admins
Run command following command to create built in auth
php artisan make:auth
Two models Users(Already exist) and Admin
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
Now open config/auth.php and make the following changes
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
Create a new Middleware RedirectIfNotAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
Changes in Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder
Open the file Http/Controller/Adminauth/AuthController.php and make the following changes
<?php
namespace App\Http\Controllers\Adminauth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (Auth::guard('admin')->check())
{
return redirect('/admin');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
public function resetPassword()
{
return view('admin.auth.passwords.email');
}
public function logout(){
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/
create new file Http/Controller/admin/employee.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use App\Admin;
class Employee extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
move to resources/views create new folder resources/views/admin
copy
resources/views/auth, resources/views/layouts & resources/views/home.blade.php
and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like
#extends('admin.layouts.app')
and your Http/routes.php look like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/login','Adminauth\AuthController#showLoginForm');
Route::post('/admin/login','Adminauth\AuthController#login');
Route::get('/admin/password/reset','Adminauth\PasswordController#resetPassword');
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::get('/admin/logout','Adminauth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'Adminauth\AuthController#showRegistrationForm');
Route::post('admin/register', 'Adminauth\AuthController#register');
Route::get('/admin', 'Admin\Employee#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Thats it open your site in browser and check
and for admin yoursiteurl/admin
Enjoy....
First, we create two models: user and admin
Then, we update the config/auth.php file:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
Now, modify the app/Http/kernel.php file:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],
'api' => [
'throttle:60,1',
],
];
Create LoginController and set the following code in it.
Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().
namespace App\Http\Controllers;
use Auth, Input;
use App\User;
use App\Admin;
class LoginController extends Controller
{
public function userLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('user');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('user.login');
}
}
public function adminLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('admin');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('admin.login');
}
}
public function profile(){
if(auth()->guard('admin')->check()){
pr(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
pr(auth()->guard('user')->user()->toArray());
}
}
}
In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.
This approach helps in avoiding the unnecessary headache of creating different user roles or types.
Though this may not sound ideal, but helps in saving lots of time.

Categories