简体   繁体   English

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

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

I am trying to make a middleware for different type of users in my Laravel 5.2 app. 我正在尝试为我的Laravel 5.2应用程序中的不同类型的用户制作中间件。 So, what is I am doing is making different middlewares for different users. 所以,我正在做的是为不同的用户制作不同的中间件。

As far as I am knowing Auth::check() will not work without musing middleware web from here . 至于我知道验证::检查(),请事先沉思中间件的网络工作在这里

So, what I have done is- 所以,我所做的是 -

routes.php 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 AdminMiddleware.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 Kernel.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 AdminController.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- 但我得到这个错误 -

在此输入图像描述

when " return Auth::user(); " called inside middleware, "return Auth::user();" 当“ 返回Auth :: user(); ”在中间件中调用时,“返回Auth :: user();” is working in other place (view and controllers) but not working like old versions of Laravel. 正在其他地方工作(视图和控制器),但不像老版本的Laravel一样工作。

Can anyone please help? 有人可以帮忙吗?

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 Response object from your middleware. 您收到的错误来自于您没有从中间件返回Response对象这一事实。 The VerifyCsrfToken middleware is trying to add a cookie to the response it gets from passing the request down the pipeline. VerifyCsrfToken中间件正在尝试将cookie添加到通过管道传递请求所获得的响应中。 In this case it is not getting a Response object but instead a string or User because a string or User was returned in your middleware. 在这种情况下,它不是获取Response对象而是获取字符串或User因为在中间件中返回了字符串或User

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. 确保您的内核文件包含会话中间件。

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 php artisan cache:清楚

composer dump-autoload composer dump-autoload

php artisan clear-compiled php artisan clear-compiled

php artisan optimize php artisan优化

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'
    ]);
});

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 . 在Laravel中,users表的默认主键是id In case, you've changed that into user_id or something, You have to mention that in your Model. 如果您已将其更改为user_id或其他内容,则必须在模型中提及。 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. 如果没有,Laravel无法为用户创建会话, Auth::attempt()将正常工作,但Auth::check()不会。 So, Make sure you've mentioned that inside the model class. 所以,确保你已经在模型类中提到过。

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

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

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