简体   繁体   English

Laravel 5.2:如何在中间件中使用auth

[英]Laravel 5.2: How to use auth in middleware

I've create a new middleware name Adminpanel 我创建了一个新的中间件名称Adminpanel

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Adminpanel
{
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role == 'admin'){
            return $next($request);
        }else{
            return redirect('admin/login');
        }
    }
}

and register middle ware 并注册中间件

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,
    'adminpanel' => \App\Http\Middleware\Adminpanel::class,
];

and route 和路线

Route::group(['middleware' => ['web','adminpanel']], function () {
Route::get('/admin/dashboard/', 'admin\Dashboard@index');
//

}); });

but when I run, It ask me Trying to get property of non-object, means I could not access Auth class here, can somebody tell me what is the mistake and how to access Auth Facade in middleware. 但是当我运行时,它问我试图获取非对象的属性,意味着我无法访问Auth类,有人可以告诉我这是什么错误以及如何在中间件中访问Auth Facade。

and this is my authentication code 这是我的验证码

public function authenticate(Request $request)
{
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'role' => 'admin'], $request->input('remember'))) 
    {
        return redirect()->intended('admin/dashboard');
    }
    else{
        return redirect('admin')->with('response',-1);
    }
}

Thanks 谢谢

It doesn't mean you couldn't access Auth class. 这并不意味着您无法访问Auth类。 It means, that user is not authenticated and Auth::user() returns NULL . 这意味着,该用户未经过身份验证, Auth :: user()返回NULL

Make sure that only authenticated users can access your route by using auth middleware for that route or first check if user is authenticated: 确保只有经过身份验证的用户可以通过使用该路由的auth中间件来访问您的路由,或者首先检查用户是否经过身份验证:

if(Auth::check() && Auth::user()->role == 'admin'){
  return $next($request);
} else {
  return redirect('admin/login');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM