Laravel 5.2 - 使用 Auth::check() 在中间件中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34584753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:57:58  来源:igfitidea点击:

Laravel 5.2 - Using Auth::check() not working in MIddleware

phplaravelmiddlewarelaravel-5.2

提问by Abrar Jahin

I am trying to make a middleware for different type of users in my Laravel 5.2 app. So, what is I am doing is making different middlewares for different users.

我正在尝试在我的 Laravel 5.2 应用程序中为不同类型的用户制作一个中间件。所以,我正在做的是为不同的用户制作不同的中间件。

As far as I am knowing Auth::check() will not work without musing middleware web from here.

据我所知,如果不从这里考虑中间件网络,Auth::check() 将无法工作。

So, what I have done is-

所以,我所做的是——

routes.php

路由文件

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});

AdminMiddleware.php

管理中间件.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            return "asd";
            //return Auth::user();
            //return redirect('home');
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        return $next($request);
    }
}

Kernel.php

内核.php

protected $routeMiddleware = [
    'auth'          => \App\Http\Middleware\Authenticate::class,
    'admin'         => \App\Http\Middleware\AdminMiddleware::class,
    'user'          => \App\Http\Middleware\UserMiddleware::class,
    'auth.basic'    => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest'         => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

AdminController.php

管理控制器.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function users()
    {
        return view('admin.users');
    }

    public function articles()
    {
        return view('admin.articles');
    }
}

But I am getting this error-

但我收到此错误-

enter image description here

在此处输入图片说明

when "return Auth::user();" called inside middleware, "return Auth::user();" is working in other place (view and controllers) but not working like old versions of Laravel.

当“ return Auth::user();”在中间件内部调用时,“return Auth::user();” 正在其他地方(视图和控制器)工作,但不像旧版本的 Laravel 那样工作。

Can anyone please help?

有人可以帮忙吗?

采纳答案by lagbox

You could potentially do something like this, adjust where needed

你可能会做这样的事情,在需要的地方进行调整

public function handle($request, Closure $next)
{
    $user = $request->user();

    if (! $user || $user->user_type != 'admin') {
        return redirect('login');
    }

    return $next($request);
}

The error you are receiving is coming from the fact that you are not returning a Responseobject from your middleware. The VerifyCsrfTokenmiddleware is trying to add a cookie to the response it gets from passing the request down the pipeline. In this case it is not getting a Responseobject but instead a string or Userbecause a string or Userwas returned in your middleware.

您收到的错误是因为您没有Response从中间件返回对象。该VerifyCsrfToken中间件试图一个cookie添加到它从传承管道请求中得到响应。在这种情况下,它不是获取Response对象而是获取字符串,或者User因为字符串或User在您的中间件中返回。

回答by Cowboy

You have added routes in web group as well so make sure your kernel file should have following middleware group.

您也已在 web 组中添加了路由,因此请确保您的内核文件应具有以下中间件组。

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

The error due to session. make sure your kernel file contains session middlewares.

会话导致的错误。确保您的内核文件包含会话中间件。

回答by Abrar Jahin

Hi @Cowboy and @lagbox , Thanks for trying to help, unfortunately they were not working, but I have solved it.

嗨@Cowboy 和@lagbox,感谢您的帮助,不幸的是他们没有工作,但我已经解决了。

I have solved it by running-

我已经通过运行解决了它-

php artisan cache:clear

composer dump-autoload

php artisan clear-compiled

php artisan optimize

php artisan 缓存:清除

作曲家转储自动加载

php artisan 清晰编译

php工匠优化

and then middleware-

然后是中间件-

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            if(strcmp( "admin" , Auth::user()->user_type ) != 0 )
                return redirect('home');
            else
                return $next($request);
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        //return $next($request);
    }
}

And Route-

和路线-

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});

回答by Bairu

I've the same issue. In my case, I'm facing this in Multiple authentication. If you're using Multiple authentications or even single authentication with different primary key name in the table instead of id, This may cause.

我有同样的问题。就我而言,我在多重身份验证中遇到了这个问题。如果您在表中使用不同的主键名称而不是 使用多重身份验证甚至单一身份验证id,这可能会导致。

In Laravel, the default primary key for the users table is id. In case, you've changed that into user_idor something, You have to mention that in your Model. If not, Laravel can't create the session for the user as a result, the Auth::attempt()will work fine but Auth::check()will not. So, Make sure you've mentioned that inside the model class.

在 Laravel 中,用户表的默认主键是id. 如果您已将其更改为user_id或其他内容,则必须在模型中提及。如果没有,Laravel 将无法为用户创建会话,结果Auth::attempt()会正常工作但Auth::check()不会。因此,请确保您在模型类中提到了这一点。

class User extends Authenticatable {
   $primaryKey = 'user_id';