Laravel多重保护身份验证失败



我正在创建一个具有多个防护的Laravel网站我的目标是能够使用会话使用passport作为管理员、员工和用户登录一切都很好但是,我无法以员工身份登录

这是git repo。请检查员工分支机构和数据库种子Git Repo

我将在这里分享步骤和代码,以查找问题所在:

  1. 我创建了必要的保护、提供者和密码代理
  2. 我更新了员工模型
  3. 我更新了RedirectIfAuthenticated和Authenticate中间件
  4. 我创建了必要的路线和控制器

这是所有这些代码:

这是config/auth.php文件,我有4个web、api、admin和employee及其提供商和密码代理:

<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'employee' => [
'driver' => 'session',
'provider' => 'employees',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => AppAdmin::class,
],
'employees' => [
'driver' => 'eloquent',
'model' => AppEmployee::class,
],
// 'users' => [
//     'driver' => 'database',
//     'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 15,
'throttle' => 60,
],
'employees' => [
'provider' => 'employees',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

这是Employee.php模型:

<?php
namespace App;
use AppTraitsPermissionsHasPermissionsTrait;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use AppNotificationsEmployeeResetPasswordNotification as EmployeeResetPasswordNotification;
class Employee extends Authenticatable
{
use Notifiable, HasPermissionsTrait;
protected $guard = 'employee';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Send the password reset notification.
*
* @param  string  $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new EmployeeResetPasswordNotification($token));
}
}

这是App\Http\Middleware:中的RedirectIfAuthenticated.php

<?php
namespace AppHttpMiddleware;
use AppProvidersRouteServiceProvider;
use Closure;
use IlluminateSupportFacadesAuth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $request
* @param  Closure  $next
* @param  string|null  $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "admin" && Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::ADMINHOME);
}
if ($guard == "employee" && Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::EMPLOYEEHOME);
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}

这是App\Http\Middleware:中的Authenticate.php

<?php
namespace AppHttpMiddleware;
use IlluminateAuthMiddlewareAuthenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param  IlluminateHttpRequest  $request
* @return string|null
*/
protected function redirectTo($request)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
if ($request->is('admin') || $request->is('admin/*')) {
return route('admin.login');
}
if ($request->is('employee') || $request->is('employee/*')) {
return route('employee.login');
}
if (! $request->expectsJson()) {
return route('login');
}
}
}

以下是员工路线:

Route::prefix('employee')->group(function() {
Route::get('/', 'EmployeeHomeController@index')->name('employee.dashboard');
Route::get('/home', 'EmployeeHomeController@index')->name('employee.home');
// Login Logout Routes
Route::get('/login', 'AuthEmployeeLoginController@showLoginForm')->name('employee.login');
Route::post('/login', 'AuthEmployeeLoginController@login')->name('employee.login.submit');
Route::post('/logout', 'AuthEmployeeLoginController@logout')->name('employee.logout');
// Password Resets Routes
Route::post('password/email', 'AuthEmployeeForgotPasswordController@sendResetLinkEmail')->name('employee.password.email');
Route::get('password/reset', 'AuthEmployeeForgotPasswordController@showLinkRequestForm')->name('employee.password.request');
Route::post('password/reset', 'AuthEmployeeResetPasswordController@reset')->name('employee.password.update');
Route::get('/password/reset/{token}', 'AuthEmployeeResetPasswordController@showResetForm')->name('employee.password.reset');
});

最后是App\Http\Controllers\Auth\Employee\LoginController.php:

<?php
namespace AppHttpControllersAuthEmployee;
use AppHttpControllersController;
use AppProvidersRouteServiceProvider;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating employees for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::EMPLOYEEHOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest:employee')->except('logout');
}
/**
* Get the guard to be used during authentication.
*
* @return IlluminateContractsAuthStatefulGuard
*/
protected function guard()
{
return Auth::guard('employee');
}
public function showLoginForm()
{
return view('auth.employee-login');
}
/**
* Handle a login request to the application.
*
* @param  IlluminateHttpRequest  $request
* @return IlluminateHttpRedirectResponse|IlluminateHttpResponse|IlluminateHttpJsonResponse
*
*/
public function login(Request $request)
{
$this->validate($request, [
'email'   => 'required|email',
'password' => 'required|min:6'
]);
$credentials = ['email' => $request->email, 'password' => $request->password];
$remember_token = $request->get('remember');
if ($res = $this->guard()->attempt($credentials, $remember_token)) {
return redirect()->intended('/employee/home');
}
return back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('employee')->logout();
return redirect('/');
}
}

问题是:

登录函数中,尝试函数返回true,但重定向将我返回登录页面,这意味着Employee/HomeController.php在其构造函数中具有中间件auth:Employee,它将我踢出并将我返回到

Authenticate我检查过:

if ($res = $this->guard()->attempt($credentials, $remember_token)) {
return redirect()->intended('/employee/home');
}

在LoginController中的if语句中,如下所示:

--dd(Auth::guard('employee'(->check(((;结果是真的

--dd(Auth::guard('employee'(->user(((它返回:

AppEmployee {#379 ▼
#guard: "employee"
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "employees"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▶]
#original: array:7 [▼
"name" => "employee"
"email" => "employee@gmail.com"
"email_verified_at" => "2020-05-05 18:16:25"
"password" => "$2y$10$15zFxGvAA2GVRkcAYFEXc.3WyOtcdlARlOMwIdSEqbU2.95NNWUJG"
"remember_token" => null
"created_at" => "2020-05-05 18:16:25"
"updated_at" => "2020-05-05 18:16:25"
]
#changes: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"

我仍然找不到问题出在哪里。任何帮助。谢谢

问题不在LoginController或问题中的逻辑中。一切都很好。然而,员工迁移是错误的,表中没有id,这就是解决方案。。所以这个问题无关紧要。

相关内容

最新更新