【问题标题】:Laravel 5 Auth::user() is empty everywhere except index() function and blade templateLaravel 5 Auth::user() 除了 index() 函数和刀片模板之外的任何地方都是空的
【发布时间】:2018-09-19 13:07:00
【问题描述】:

我已经尝试了一段时间来解决这个问题,但我没有找到任何结论性的解决方案。基本上我正在尝试根据登录的用户检索客户端列表,但我无法在控制器中的任何位置检索用户对象,除了返回视图的 index() 函数以及显示已登录的刀片模板在用户名中。

这是我的 ClientController.php:

<?php

namespace App\Http\Controllers;

use App\Http\Models\Client;
use App\Http\Requests\GetClientsRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ClientController extends Controller
{
    protected $user;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

       $this->middleware(function ($request, $next) {
           $this->user = Auth::user();

           return $next($request);
       });
    }

    /**
     * Show the clients page.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        Log::info("client user: " . print_r($this->user, 1));
        return view('page');
    }

    public function getClients()
    {
        $currentUser = Auth::user();

        if ($currentUser) {
            $clients = Client::with('account')
                    ->where('user_id', $currentUser->account)
                    ->get();

            $collection = collect($clients);

            return response($collection->toArray());
        }
    }
}

Log in index 函数打印出用户对象没有问题 - 但是在 getClients() 函数中调用它时,它是空的。我也尝试在__construct() 中使用它:

$this->middleware('auth');

根据我使用的 Laravel 模板,但每当我调用 getClients API 路由时,我总是会收到 401 Unauthorized 错误。

这是我的 api.php 路由文件(虽然目前只使用 getClients 调用):

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('welcome-message', 'DashboardController@getWelcomeMessage');

Route::prefix('clients')->group(function () {
    Route::get('/', 'ClientController@getClients');
    Route::get('/{clientId}', 'ClientController@getClient');
    Route::post('/', 'ClientController@postCreateClient');
    Route::put('/{clientId}', 'ClientController@putUpdateClient');
});

还有我的web.php 路由文件:

<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Auth::routes();

Route::get('/', 'HomeController@index')->name('dashboard');
Route::get('/clients', 'ClientController@index')->name('clients');

系统知道我已登录,因为我什至根本无法访问客户端仪表板,所以我不明白为什么我无法从函数中的 Auth::user() 获得结果 - 除非我是不是在错误地使用中间件?

【问题讨论】:

    标签: laravel-5 middleware


    【解决方案1】:

    您必须使用auth:api 中间件来允许API authentication

    为此,请将此中间件添加到您的 API 路由中,在这种情况下省略在 __constructor 中添加中间件。

    Route::group([
        'prefix' => 'clients',
        'middleware' => ['auth:api']
    ], function(){
        Route::get('/', 'ClientController@getClients');
        // ... etc
    });
    

    确保您拥有有效的访问令牌来访问您的 API。当你的 API 与 JS 前端一起使用时,read about it 在 Laravel 文档中。

    请注意,“网络”身份验证(中间件:auth)使用与 API 身份验证(中间件:auth:api)不同的机制来对用户进行身份验证。

    【讨论】:

    • 我仍然收到 401 Unauthorized 错误。我尝试安装 Laravel Passport,但似乎没有任何效果,即使我遵循了文档。但是你是正确的,因为用户只通过'auth'而不是'auth:api'进行身份验证,所以我不知道该怎么做:(
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2016-03-08
    • 2015-04-16
    • 2016-12-18
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多