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();
}
Related
Problem:
On my index page, authenticated users and guests should be able to view and use the page unless they want to save something. I tried to log in so that I could save the data and was redirected to an authenticated page which is a profile page. I tried dumping Auth::user() on the profile page, it returns the user logged in data, tried dumping it again on the index page then it returns null.
I'm using the latest version of Laravel.
I've googled some of the same problems I have and the closest one is this Auth::user() returns null. I tried following the answer provided but still, it returns null.
web.php
Route::group(['middleware' => 'web'], function () {
Route::get('/', [IndexController::class, 'index'])->name('index.page');
Auth::routes();
Route::group(['middleware' => ['auth:user']], function() {
Route::get('/user/profile', [UserController::class, 'profile'])->name('user.profile');
});
Route::group(['prefix' => 'admin', 'middleware' => ['auth:admin']], function() {
Route::get('dashboard',[DashboardController::class, 'index'])->name('admin.dashboard');
});
})
auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'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' => 15,
],
],
This is the only modification I did from the middleware.
RedirectIfAuthenticated.php
foreach ($guards as $guard) {
if ($guard === "admin" && Auth::guard($guard)->check()) {
return redirect('/admin/dashboard');
}
if ($guard === "user" && Auth::guard($guard)->check()) {
return redirect('/user/profile');
}
if (Auth::guard($guard)->check()) {
return redirect('/');
}
}
I added $guard for the User and Admin model
User.php
protected $guard = 'user';
Admin.php
protected $guard = 'admin';
If you have any questions, feel free to ask and thanks for the help!
But i guess the customized Auth.php has a problem
foreach ($guards as $guard) {
if ($guard === "admin" && Auth::guard($guard)->check()) {
return redirect('/admin/dashboard');
}else{
if ($guard === "user" && Auth::guard($guard)->check()) {
return redirect('/user/profile');
}else{
return redirect('/');
}
}
}
I can share the solution that worked for me. I switched from Passport to Sanctum.
I'm working on a Laravel 8 project with Inertia.js. In the login function, I can use Auth::user() to get the user. However, after login, the other functions get a null in Auth::user(). I'm not sure what's wrong. Can someone help me?
I considered that Laravel Auth uses sessions to recognize the current user, so I tried to list session by dd($request->session()->all()); before and after login. And the session value of "_token" does not change.
Login function
public function handleProviderCallback(Request $request)
{
// user from socialite
$user = \Socialite::with('portal')->user();
// user here in database
$account = User::where('account', $user->id)->first();
if (!$account) {
User::create([
'account' => $user->id,
]);
$account = User::where('account', $user->id)->first();
}
Auth::login($account);
//dd(Auth::user());
return Inertia::render('Home/index');
}
function which gets null
public function getUser(Request $request)
{
dd(Auth::user());
return Auth::user();
}
Here is some information that may or may not is needed.
web.php
Route::get('/login', 'Auth\PortalLoginController#redirectToProvider')
->name('login');
Route::get('getUser', ['as' => 'getUser',
'uses' => 'Auth\PortalLoginController#getUser']);
Route::get('session', ['as' => 'session',
'uses' => 'Auth\PortalLoginController#listSession']);
auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Laravel needs auth middleware to check authentication and initialize Auth service. So you need to add auth middleware to all your routes which you want to access Auth::user()
So update your routes in routes/web.php
Route::get('/login', 'Auth\PortalLoginController#redirectToProvider')->name('login');
Route::get('getUser', ['as' => 'getUser', 'uses' => 'Auth\PortalLoginController#getUser'])->middleware('auth');
Route::get('session', ['as' => 'session', 'uses' => 'Auth\PortalLoginController#listSession'])->middleware('auth');
'Route [login] not defined ..'
I'm new to Laravel. I want to make a login system myself, but I still have not solved this error. I am logging in but the user appears blank on the other page, I still cannot control it. I want to use the user restrictions on other pages, how can I do this.
web.php
Route::post('login', [userLogin::class, 'loginPost'])->name('login.post');
Route::get('student/home', [studentHome::class, 'index'] )->name('student.home')->middleware('auth:students');
Route::get('/', function () {
return view('login');
userLoginController.php
public function loginPost(Request $request)
{
if(auth::guard('students')->attempt(['email'=>$request->student_mail,'password'=>$request->student_password],false))
{
//dd(Auth::guard('students')->check());
return redirect()->intended('student.home');
}
else
{
echo "yannlış";
}
}
auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'students' => [
'driver' => 'session',
'provider' => 'students',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Models\students::class,
],
You are missing the login route which is used to display the login form. Try naming your root:
Route::get('/', function () {
return view('login');
})->name('login');
Or you can add a separate route depending on what you are looking for.
Route::get('login', [UserLogin::class, 'showLoginForm'])->name('login');
I run into this error when i was learning creating an API using laravel passport middleware, it redirects by default to the GET login route, so i had to add like the previous comment said in my web.php.
Route::get('/login', function () {
return view('login');
})->name('login');
I am trying to login from two different model using same login form. I have defined admin guard in config/Auth.php. But when I define admin guard in Foundation/AuthenticateUsers it checks the database table to validate the user but redirects back to same login form.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
Foundation/AuthenticatUsers
protected function guard()
{
return Auth::guard('admin');
}
public function login(Request $request)
{
$credentials = $this->credentials($request);
if (Auth::guard('web')->attempt($credentials, $request- >has('remember'))) {
return $this->sendLoginResponse($request);
}
elseif(Auth::guard('admin')->attempt($credentials, $request->has('remember')))
{
return $this->sendLoginResponse($request);
}
}
Admin guard redirects to login page because of middleware auth, i think you need to do something like this
public function __construct()
{
$this->middleware('auth:admin');
}
Read this Protecting Routes, part "Specifying A Guard"
I am using laravel 5.2 and I am trying to log in with more than one auth guard but only the default is working.
This is my code.
Guards
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins'
]
],
Providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
Authenticate Middleware
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
Routes
Route::get('/foo', function(){
if (Auth::guard('web')->attempt(['email' => 'bale#mail.com', 'password' => 'gareth'])){
return redirect('/');
}else{
return 'No!';
}
});
Route::get('/bar', function(){
if (Auth::guard('admin')->attempt(['email' => 'lionel#mail.com', 'password' => 'password'])){
return redirect('/');
}else{
return 'No!';
}
});
Both routes return true when the attempt method is called but only the web guard actually logs a user in but if i switch the default guard to admin, the admin guard works and the web guard doesn't.
Can someone help me in solving this?
I found a github repo that solved my problem.
https://github.com/gregoryduckworth/laravel-multi-auth