Laravel自定义中间件返回卫士为false



我正在laravel 9中使用自定义中间件和自定义保护进行自定义身份验证,但我的自定义中间件中的保护返回false,这是我的代码

<?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"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
/*
|--------------------------------------------------------------------------
| 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' => AppModelsUser::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => AppModelsAdmin::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 each reset token will 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,
],
],
/*
|--------------------------------------------------------------------------
| 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,
];

这是我的内核

class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// AppHttpMiddlewareTrustHosts::class,
AppHttpMiddlewareTrustProxies::class,
IlluminateHttpMiddlewareHandleCors::class,
AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateSessionMiddlewareStartSession::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
'api' => [
// LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
'signed' => AppHttpMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
'admin' => AppHttpMiddlewareAdminMiddleware::class,
];
}

中间件注册为";管理员";这是我的中间件,当我添加卫士gu 时返回false

<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $request
* @param  Closure  $next
* @return mixed
*/
public function handle(Request $request, Closure $next){
dd(Auth::guard('admin')->check());
// dd('hh');
if(Auth::guard('admin')->check() ){
return $next($request);
}
return redirect()->route('admin.login');
}
}

这是我的登录控制器

<?php
namespace AppHttpControllersAuth;
use AppHttpControllersController;
use AppModelsAdmin;
use IlluminateHttpRequest;
use AppProvidersRouteServiceProvider;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesSession;
// use IlluminateFoundationAuthAuthenticatesUsers;
class AdminLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
// use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
// protected function authenticated()
// {
//    return redirect()->route('admin.dashboard');
// }
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
// $this->middleware('guest:admin')->except('logout');
}
public function showLoginForm()
{
return view('login');
}
public function adminLogin(Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only('email','password');
$remember_me = $request->has('remember') ? true : false;
if (Auth::guard('admin')->attempt($credentials, $remember_me)) {
// $user = Auth::guard('admin')->user()->id;
// $user = Admin::find($user);
// Auth::guard('admin')->login($user);
return redirect()->route('admin.dashboard');
}  
// dd(Auth::guard('admin')->check());
return redirect()->route('admin.login')->with('error', 'Email or Password is incorrect!');
}
}

最后,这是我的路由服务提供商,我在中间件中添加了路由

<?php
namespace AppProviders;
use IlluminateCacheRateLimitingLimit;
use IlluminateFoundationSupportProvidersRouteServiceProvider as ServiceProvider;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;
use IlluminateSupportFacadesRoute;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
Route::middleware('admin')
->prefix('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php')); 
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}

我已经尝试了所有的东西,这和我在其他项目中使用的东西完全一样,它在laravel 7上有效,但这个版本是laravel 9,它在这里不起作用,我检查了文档,我没有发现任何与此相关的东西,感谢

在您的AdminMiddleware中,您可以尝试使用auth('admin')->check();而不是Auth::guard('admin')->check();

最新更新