JWT Laravel authenthication and middleware - laravel

I have a web site bult with laravel and vuejs
I have used jwt for login, all works fine
Only the middleware always reyrns false to:
//if ($this->auth->check() )
//if ($this->auth->api->check() )
if (Auth::guard('api')->check())
{
return $next($request);
}
else
{
return redirect()->to('/admin/index');
}
All these return false and when I refresh I get back to the home page
I have also made the default driver api in config/auth.php but still the check returns false
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Regards

Related

Argument 2 passed to Illuminate\\Auth\\SessionGuard::__construct() must implement interface Illuminate\\Contracts\\Auth\\UserProvider

This is my auth.php file
return [
'defaults' => [
'guard' => 'salon_emp',
// 'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'salon_emp' => [
'driver' => 'jwt',
'provider' => 'salon_emp'
],
'app' => [
'driver' => 'session',
'provider' => 'client'
]
],
'providers' => [
'salon_emp' => [
'driver' => 'eloquent',
'model' => SalonEmployee::class,
],
'client' => [
'driver' => 'eloquent',
'model' => Client::class
]
],
This is my login function in my LoginController
public function login(LoginRequest $request)
{
if (auth('app')->attempt($request->validated())) {
auth('app')->user()->tokens()->delete();
return apiResponse([
'message' => 'Login successful!',
'token' => auth('app')->user()->createToken(auth('app')->user()->name)->plainTextToken
]);
} else {
return apiResponse([
'message' => 'Login not successful!',
], Response::HTTP_UNAUTHORIZED);
}
}
I am also using sanctum for authentication
in my routes file i am using the auth:sanctum middleware to secure my routs, for example:
Route::get('/test',function ()
{
dd('ss');
})->middleware('auth:sanctum');
how ever i get this error whenever i try to access it
Argument 2 passed to Illuminate\\Auth\\SessionGuard::__construct() must implement interface Illuminate\\Contracts\\Auth\\UserProvider, null given, called in \vendor\\laravel\\framework\\src\\Illuminate\\Auth\\AuthManager.php on line 128",
i have tried changing providers and drivers but no luck
I added this line to sanctum.php
'guard' => 'app'
and it worked fine

Laravel Sanctum middleware with OR condition

I am using Laravel Sanctum for Token Based Authentication.
I have created a customer guard for customer. For Other users its default users table.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'customer' => [
'driver' => 'sanctum',
'provider' => 'customers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => Customer::class,
],
],
I was authenticating all other users using middleware' => ['auth:sanctum'] now for the given particular route, I want customer guard can also access this Route. But there is no such Functionality provided by Laravel for OR condition.
Route::group(['as' => 'business', 'prefix' => 'business', 'middleware' => ['auth:sanctum']], function () {
Route::get('/categories', [BusinessCategoryController::class, 'listBusinessCategories'])->name('business-category');
Route::get('/categories/{parentId}', [BusinessCategoryController::class, 'listBusinessSubCategories'])->name('business-sub-category');
});
I just want middleware' => ['auth:sanctum'] or ['auth:customer']

Laravel 8 Authentication doesn't work after upgrade form 7

As the title says, it just stopped working out of sudden. I have a custom guard:
config.auth.php
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
.....
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
The user (or shall I say admin?) gets authenticated through login controller:
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password, ])) {
return redirect()->intended('/check');
but the route 'check' returns null
Route::get('/check', function () {
$user = auth()->user();
dd($user);
});
.env session part:
SESSION_DRIVER=file
SESSION_LIFETIME=1200
No any errors logged out, no any clue whats wrong. This app also has laravel Passport for API logins, which work fine
Try this, replace provider with this:
'providers' => [
'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ],

Laravel Sanctum SPA Authenticate Different User Table

So Basically we have two tables, one is the users table which is for the users of the site. The other is for people signing up for a webinar. We call this table Attendants. I want people to log into Attendant, and have Sanctum validate that, but I am running into issues. I get a 401 error.
I am using
Laravel 7
Vue 2
Axios
Env
SESSION_DRIVER=database
SESSION_DOMAIN=.server.local
SANCTUM_STATEFUL_DOMAINS=server.local,localhost,127.0.0.1
Cors
'paths' => [
'api/*',
'sanctum/csrf-cookie',
'webinars/newplatform/*'
],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Guards and providers
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'web_attendant' => [
'driver' => 'session',
'provider' => 'attendants',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'sanctum' => [
'driver' => 'sanctum',
'provider' => 'users',
],
'sanctum_attendant' => [
'driver' => 'sanctum',
'provider' => 'attendants',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Modules\User\Entities\User::class,
'table' => 'users'
],
'attendants' => [
'driver' => 'eloquent',
'model' => Modules\Webinar\Entities\Attendant::class,
],
],
Main.js
Vue.prototype.$axios = require('axios');
Vue.prototype.$axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Vue.prototype.$axios.defaults.baseURL = frontPath;
Vue.prototype.$axios.defaults.withCredentials = true;
Login
this.$axios.get('/sanctum/csrf-cookie').then(response => {
this.$axios.post(`/webinar/${this.webinar}/login`, {
email: this.email,
password: this.password,
}).then(({data}) => {
//
})
});
So, When I try to login to the attendant, I get a successful Attendant model back, but any attempts made to the sanctum routes come back as 401.
Backend Login - Returns Attendant model
Auth::guard('web_attendant')->login($attendant);
return Auth::guard('web_attendant')->user();
Routes
Route::group(['middleware' => [ 'auth:sanctum_attendant' ] ], function()
{
Route::get('/webinar/{webinar}/attendant', [AuthController::class, 'attendant']);
Route::get('/webinar/{webinar}', [PlatformController::class, 'show']);
});
However, if i switch to login to the User Model instead of the Attendant model, the sanctum routes work
Auth::attempt(['email' => request()->email, 'password' => request()->password]);
return Auth::user();
Route::group(['middleware' => [ 'auth:sanctum' ] ], function()
{
Route::get('/webinar/{webinar}/attendant', [AuthController::class, 'attendant']);
Route::get('/webinar/{webinar}', [PlatformController::class, 'show']);
});
So I feel like I am missing something here. Any help would be appreciated
I found out the Sanctum guard defaults to the web guard, which uses the Users Table. So Sanctum was trying to authenticate the Attendant with the users table.
public function __invoke(Request $request)
{
if ($user = $this->auth->guard(config('sanctum.guard', 'web'))->user()) {
return $this->supportsTokens($user)
? $user->withAccessToken(new TransientToken)
: $user;
}
I got around this by adding
config(['sanctum.guard' => 'web_attendant']);
To my api.php file. Since My admin panel authenticates users and webinars authenticate attendants, I can't hard code in a guard in the sanctum.php config file
set a different table name in config/sanctum.php
Try this solution
this work for me

Laravel Login to Admin dashboard redirect to 404 page after enable AuthenticateSession middleware

Im working in simple blog site using laravel which has 2 parts , blog site for users and admin dashboard
It is all works good before but after uncomment below line in Http/Kernal.php
\Illuminate\Session\Middleware\AuthenticateSession::class,
failed to login and redirect to admin dashboard and it is redirect to 404 page.
I just want to use AuthenticateSession middleware because , i want to use
logoutOtherDevices function for website users
Auth::logoutOtherDevices($request->input('new-password'));
when i comment out this line \Illuminate\Session\Middleware\AuthenticateSession::class, again it is working normal .
please help me to solve this issue .
I have users table used for login users and admin table for login admin to dashboard
here is table for admin :
here is config/auth.php :
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Model\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Model\Admin::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
]
],
];
here is admin login function :
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password,'status'=>1], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('admin.dashboard'));
}else{
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
}

Resources