Laravel Middleware将用户信息返回为null

时间:2018-04-09 08:34:34

标签: laravel authentication laravel-5 middleware

我创建了一个中间版以防止用户不插入或更新任何内容。我在Laravel 5.6

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
class LimitDemoUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userId = Auth::id();
        if(request()->method() != "GET" && request()->method() != "HEAD" && $userId == 6) {
            abort(403);
        }
        return $next($request);
    }
}

我将它注册到内核(LimitDemoUser)

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\LimitDemoUser::class,

];

但是当我dd(Auth :: id());我得到了null而不是登录用户ID

我在这里缺少什么?

我想我没有为routemiddleware添加任何东西

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

];

我的LoginController在下面。也许它可能会有所帮助

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController 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 $redirectTo = '/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function logout()
    {
        $this->guard()->logout();

        return redirect()->route('login');
    }

}

4 个答案:

答案 0 :(得分:0)

您的loginController应如下所示:

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

如果您想获取用户ID,则应该是用户类。

if (Auth::check())
{
    // The user is logged in...
    Auth::user()->id;
}
else
{
    echo "You are not logged in";
}

答案 1 :(得分:0)

尝试将您的web.php更改为

Route::middleware(['limitdemouser'])->group(function () {
  Auth::routes();
});

你的$ routeMiddleware是

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'limitdemouser' => \App\Http\Middleware\LimitDemoUser::class,
];

如果不行,请告诉我

答案 2 :(得分:0)

我在此页面中找到了解决方案。 https://laracasts.com/discuss/channels/laravel/current-user-in-middleware

OP表示

i have added the following code in the global middleware and nou is het working 
\App\Http\Middleware\EncryptCookies::class, \Illuminate\Session\Middleware\StartSession::class,

很脏但是很有效。我不认为这是最好的做法,但它解决了这个问题。既然我们发现了这个问题,那么有人可以建议一个合适的解决方案吗?

答案 3 :(得分:0)

\App\Http\Middleware\LimitDemoUser::class添加到web中间件组数组的末尾。

protected $middlewareGroups = [
    'web' => [
        ...,
        \App\Http\Middleware\LimitDemoUser::class,
     ]
];