Multi-Auth Auth::user() Showing null Laravel 5.8 - php

I am implementing multiple authentication as I have 3 different user groups. I am trying the following steps.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:admin')->except('logout');
$this->middleware('guest:manager')->except('logout');
$this->middleware('guest:vendor')->except('logout');
}
public function showAdminLoginForm()
{
return view('auth.login', ['url' => 'admin']);
}
public function adminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/admin');
}
return back()->withInput($request->only('email', 'remember'));
}
public function showManagerLoginForm()
{
return view('auth.login', ['url' => 'manager']);
}
public function managerLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('manager')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/manager');
}
return back()->withInput($request->only('email', 'remember'));
}
public function showVendorLoginForm()
{
return view('auth.login', ['url' => 'vendor']);
}
public function vendorLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('vendor')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/vendor');
}
return back()->withInput($request->only('email', 'remember'));
}
}
AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function dashboard()
{
dd(auth()->user());
return view('admin');
}
}
ManagerController and VendorController are same As AdminController.
Web.php
Route::view('/', 'welcome');
Auth::routes();
Route::prefix('admin')->group(function () {
Route::get('/login', 'Auth\LoginController#showAdminLoginForm');
Route::post('/login', 'Auth\LoginController#adminLogin');
Route::get('/register', 'Auth\RegisterController#showAdminRegisterForm');
Route::post('/register', 'Auth\RegisterController#createAdmin');
});
Route::prefix('manager')->group(function () {
Route::get('/login', 'Auth\LoginController#showManagerLoginForm');
Route::post('/login', 'Auth\LoginController#managerLogin');
Route::get('/register', 'Auth\RegisterController#showManagerRegisterForm');
Route::post('/register', 'Auth\RegisterController#createManager');
});
Route::prefix('vendor')->group(function () {
Route::get('/login', 'Auth\LoginController#showVendorLoginForm');
Route::post('/login', 'Auth\LoginController#vendorLogin');
Route::get('/register', 'Auth\RegisterController#showVendorRegisterForm');
Route::post('/register', 'Auth\RegisterController#createVendor');
});
Route::view('/home', 'home')->middleware('auth');
Route::get('/admin', 'AdminController#dashboard');
Route::get('/manager', 'ManagerController#dashboard');
Route::get('/vendor', 'VendorController#dashboard');
RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "admin" && Auth::guard($guard)->check()) {
return redirect('/admin');
}
if ($guard == "manager" && Auth::guard($guard)->check()) {
return redirect('/manager');
}
if ($guard == "vendor" && Auth::guard($guard)->check()) {
return redirect('/vendor');
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
config.auth.php
<?php
return [
'defaults' => [
'guard' => 'admin',
'passwords' => 'admins',
],
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'manager' => [
'driver' => 'session',
'provider' => 'managers',
],
'vendor' => [
'driver' => 'session',
'provider' => 'vendors',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'managers' => [
'driver' => 'eloquent',
'model' => App\Manager::class,
],
'vendors' => [
'driver' => 'eloquent',
'model' => App\Vendor::class,
],
],
'passwords' => [
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'managers' => [
'provider' => 'managers',
'table' => 'password_resets',
'expire' => 60,
],
'vendors' => [
'provider' => 'vendors',
'table' => 'password_resets',
'expire' => 60,
],
],
];
When I am trying to get the Auth::user() by doing dd() at AdminController, it shows me null because of multi-auth. Though it logged in successfully. I assume I am not using proper guard for the admin. But at the same time I have no clue how to fix this. Please help me out.

In multi authentications:
We can access authenticated user directly using Auth::user(). It will return the authentication by default guard = 'users'.
For other authentication, we should user guard('guard_name').
In your case, you should use Auth::guard('admins')->user() instead of Auth::user().

Everything seems alright. But you have missed adding web middleware for routes.
Please edit your web.php like this and it will work.
Route::group(['middleware' => ['web']], function () {
// all your routes use Auth() besides login route should be encapsulated and go inside this.
});
it is because web middleware has session class, check-in app.Http/kernel.php
\Illuminate\Session\Middleware\StartSession::class,

Related

laravel breeze Multi Auth - Admin Guard with two diffirent registration

I'm using laravel breeze as auth scaffolding package.I want to create Multiple Authentication using laravel guards for two different registration form for two User Types (Admin, User).
The Main Idea of what I want to achieve :
I have two tables in the database one for admins and another for users what I want to achieve is if the admins choose to register an account as admin it will display a register form with specified fields for admin. after that I want to check if the user is logged in as admin or user if is logged in as admin is will redirect him/her to specified dashboard made only for admins.
It works fine for registration, but can't login as a admin here is a simple explanation of what I want to achieve:
app\Models\Admin.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'admins';
protected $fillable = [
'name',
'email',
'password',
];
config\auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
// Admin guards
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
app\Http\Middleware\RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
// dd($guards);
foreach ($guards as $guard) {
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
break;
}
}
return $next($request);
}
}
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\RegisteredUserController;
use App\Http\Controllers\Admin\AuthenticatedSessionController;
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
require __DIR__ . '/auth.php';
Route::get('admin/dashboard', function () {
return view('backend.dashboard');
})->middleware(['auth:admin'])->name('admin.dashboard');
Route::get('/admin-register', [RegisteredUserController::class, 'create'])
->middleware('guest:admin')
->name('admin.register');
Route::post('/admin-register', [RegisteredUserController::class, 'store'])
->middleware('guest:admin');
Route::get('/admin-login', [AuthenticatedSessionController::class, 'create'])
->middleware('guest:admin')
->name('admin.login');
Route::post('/admin-login', [AuthenticatedSessionController::class, 'store'])
->middleware('guest:admin');
Route::post('/admin-logout', [AuthenticatedSessionController::class, 'destroy'])
->name('admin.logout')
->middleware('auth:admin');
app\Http\Controllers\Admin\AuthenticatedSessionController.php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
public function create()
{
return view('admin.login');
}
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect('admin/dashboard');
}
public function destroy(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
app\Http\Controllers\Admin\RegisteredUserController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class RegisteredUserController extends Controller
{
public function create()
{
return view('admin.register');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = Admin::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect('admin/dashboard');
}
}
app\Http\Requests\Admin\LoginRequest.php
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
After 3 days effort i found a solution myself.
In the function authenticate() in app\Http\Requests\Admin\LoginRequest.php. I have replaced Auth::attempt(...) by Auth::guard('admin')->attempt(...)
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::guard('admin')->attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
Now it works fine for admin login and register
Ok, so my project is a bit different and not gives a 100% answer but I decided to
leave these here, it may help someone
app/Http/Requests/Auth/LoginRequest.php
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (!Auth::attempt($this->only('email', 'password'), $this->filled('remember')) ||
!auth()->user()->isAdmin() <------------ added
) {
Auth::logout(); <------------ added
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
I added the 'isAdmin' function to the user model, it isn't pre built

I built up authentication in Laravel but unsuccessful

In my project, I just need one authentication for admins and not for users and also have users table in my database but I don't want to use it in the authentication and in Admins table I want to use 'AD_AdminEmail' field as email and 'AD_AdminPassword' as authentication password and admins routes separated to management.php file.
These codes below not working and no errors but they redirect me to the login page again and Passwords in database hashed with laravel Hash::make() but Auth::attempt do not recognize it as hashed one and send a select query with plain password not hashed yet.
Here are My web route Codes:
Route::get('/login', [ 'as' => 'login', 'uses' => function() {
return view('LoginAndRegister');
}])->name('login');
Route::post('/ManagerLogin', 'Auth\LoginController#Authenticate');
Here are My LoginController Codes:
<?php
namespace App\Http\Controllers\Auth;
use App\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function username()
{
return 'AD_AdminEmail';
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'AD_AdminPassword');
}
protected function validateLogin(Request $Request){
$this->validate($Request, [
$this->username() => 'required|email,',
'AD_AdminPassword' => 'required|min:8',
]);
}
public function Show()
{
return view('LoginAndRegister');
}
public function Authenticate(\Illuminate\Http\Request $Request)
{
$AdminEmail = $Request->input('AD_AdminEmail');
$AdminPassword = $Request->input('AD_AdminPassword');
if (Auth::attempt([
'AD_AdminEmail' => $AdminEmail,
'AD_AdminPassword' => $AdminPassword
], false))
echo 200 . "OK";
else
echo 400 . "Problem Found";
}
public function Logout()
{
Session::flush();
Auth::logout();
return back();
}
}
Here are My Admin model Codes:
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $fillable = ['AD_AdminEmail', 'AD_AdminPassword'];
protected $hidden = ['AD_AdminId', 'remember_token',];
protected $primaryKey = 'AD_AdminId';
protected $guarded = ['AD_AdminId'];
protected $table = 'Admins';
use Notifiable;
public function getEmailAttribute() {
return $this->AD_AdminEmail;
}
public function setEmailAttribute($Value)
{
$this->attributes['AD_AdminEmail'] = strtolower($Value);
}
public function getAuthPassword()
{
return $this->AD_AdminPassword;
}
public function setPasswordAttribute($Value)
{
$this->attributes['password'] = bcrypt($Value);
}
}
Here are My config>auth.php Codes:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admins',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];

Multiple auth login does not redirect to the right link

I am enhancing a system with a user login present (for staffs) and I want to create another login instance for clients.
So I have set up the guards and coded the rest as follows
// config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
],
'client-api' => [
'driver' => 'token',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
// app/Client.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Client extends Authenticatable
{
use Notifiable;
protected $guard = 'clients';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
// routes/web.php
Route::prefix('/client')->name('client.')->namespace('Client')->group(function(){
Route::namespace('Auth')->group(function(){
//Login Routes
Route::get('/login','LoginController#showLoginForm')->name('login');
Route::post('/login','LoginController#login');
Route::post('/logout','LoginController#logout')->name('logout');
});
Route::get('/', 'HomeController#index')->name('home');
});
// app/Http/Controllers/Client/Auth/LoginController.php
namespace App\Http\Controllers\Client\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function showLoginForm() {
return view('auth.client.login');
}
public function login(Request $request) {
$this->validator($request);
if(Auth::guard('client')->attempt(['CustomerNo' => $request->username, 'password' => $request->password],$request->filled('remember'))) {
return redirect()
->intended(route('client.home'))
->with('status','You are Logged in as Admin!');
}
return $this->loginFailed();
}
private function validator(Request $request)
{
$rules = [
'username' => 'required|exists:clients,CustomerNo',
'password' => 'required',
];
$messages = [
'username.exists' => 'These credentials do not match our records.',
];
$request->validate($rules,$messages);
}
private function loginFailed(){
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
public function logout()
{
Auth::guard('client')->logout();
return redirect()
->route('client.login')
->with('status','You are logged out!');
}
}
// app/Http/Middleware/Authenticate.php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (Auth::guard('client')->check()) {
return redirect('/client');
} else {
return redirect('/home');
}
if (! $request->expectsJson()) {
return route('login');
}
}
}
// app/Http/Middleware/RedirectIfAuthenticated.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "client" && Auth::guard($guard)->check()) {
return redirect(route('client.home'));
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
// app/Http/Controllers/Client/HomeController.php
namespace App\Http\Controllers\Client;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth:client');
}
public function index()
{
return view('client.home');
}
}
I have tried to login after finishing all this but it seems to keep redirecting me back to staff's (default user login) login page and a quick check at the session dd
#session: Store {#195 ▼
#id: "wQTohtl4aNaSZvYZ9ru3oqltcSqs4VhWb4SV42t2"
#name: "portal_session"
#attributes: array:5 [▼
"_token" => "R6EyBlq0iNyfDh1V8Ogmta6U3uOhvJ0gcj7a2RMb"
"url" => array:1 [▼
"intended" => "https://mywebsite.com/home"
]
"_flash" => array:2 [▼
"old" => []
"new" => []
]
"_previous" => array:1 [▼
"url" => "https://mywebsite.com/client/login"
]
"login_client_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
]
#handler: FileSessionHandler {#194 ▼
#files: Filesystem {#95}
#path: "/home/mywebsite/storage/framework/sessions"
#minutes: 1440
}
#started: true
}
Is there any part where i did wrongly? Any advice is appreciated. Thanks in advance.

How to use both web and api with two kind of users in Laravel?

I am doing a RESTful API (for a mobile app) and a web interface using the blade engine. I have two kinds of users, one is a "gestionnaire" (for the web interface) and the other one is a "client" (for the mobile app).
Right now I can authenticate the user "gestionnaire" using the php artisan make:auth command, but I cannot authenticate the client even though I modified the auth.php as follows:
'defaults' => [
'guard' => 'web',
'passwords' => 'clients',
],
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'clients',
'hash' => false,
],
'web' => [
'driver' => 'session',
'provider' => 'gestionnaires',
],
],
'providers' => [
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
'gestionnaires' => [
'driver' => 'eloquent',
'model' => App\Gestionnaire::class,
],
],
'passwords' => [
'clients' => [
'provider' => 'clients',
'table' => 'password_resets',
'expire' => 60,
],
],
At the moment my controllers look like this :
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
And this :
class AuthController extends Controller
{
public function login(Request $request) {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
//'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
public function user(Request $request)
{
return response()->json($request->user());
}
}
My routes in web.php are looking like this :
Route::get('/', function () { return view('welcome'); });
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
And in api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'Auth\AuthController#login')->name('login');
Route::post('register', 'Auth\AuthController#register');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'Auth\AuthController#logout');
Route::get('user', 'Auth\AuthController#user');
});
});
With this code
I am able to connect through the web interface but not through the API. I am using Postman to process request but I am receiving the following message : Unauthorized when I am trying to sign in.
I already checked the body of my request (the email and password) and it is correct.
Does anybody have an idea on what I should do ?
You can use Auth::shouldUse('api'); in api.
OR
You can create middleware for that
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use App\User;
class ConditionalApisHandler
{
public function handle($request, Closure $next)
{
Auth::shouldUse('api');
return $next($request);
}
}
In api.php
Route::group(['middleware' => 'conditionalApisHandler'], function(){
Route::post('example','API\ExampleController#example');
});

I am trying to implement laravel 5.2 multiple authentication for user and admin . But authentication user provider[] is not defined error is given

I have followed this questions asnwer
Can anyone explain Laravel 5.2 Multi Auth with example
to implement multiple table authentication using admin and user table . I have done all steps stated above such as added admin as provider , guard in config/auth.php, created auth controller for admin , created a middleware for admin . But after i run my project it say authentication user provider[] is not defined . But i defined provider for admin and user in config/auth.php .I have used different login and registration form, controller for user and admin.When the user or admin logged in then i want to show user or admin name in nav bar. To do this I used auth guard as stated in laravel docs(the code in attachment of master file html) . I have stucked with this error for 6 days . I need your help eagerly . Here is my attaches
config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
routes.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
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', 'AdminController#index');
});
app/Http/Controllers/AdminAuth/AuthController.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;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
//protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
}
Admin.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Contracts\View\View;
class AdminController extends Controller
{
protected $guard = 'admin';
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
Admin middleware
<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfNotAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
Master layout for showing admin
<!-- Authentication Links -->
#if (Auth::guard('admin')->guest())
<li>Login</li>
<li>Register</li>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::guard('admin')->user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li><i class="fa fa-btn fa-sign-out"></i>Logout</li>
</ul>
</li>
#endif
I Think this will be helpful.
http://blog.sarav.co/multiple-authentication-in-laravel/
Why don't you give it a try using the built in user model and extending admin with it.

Categories