簡體   English   中英

是否可以在未經身份驗證的路由上使用 Auth::user()?

[英]Is it possible to use Auth::user() on non-authenticated routes?

這一定是一件非常簡單的事情,但我在 Laravel 中沒有很多經驗,我一直在尋找和努力,但沒有運氣。

我正在處理一個現有的項目,它有一些使用auth:api中間件的路由,如下所示:

Route::group(['namespace' => 'Api', 'prefix' => 'api', 'middleware' => 'auth:api', 'throttle:100,1'], function () {

    // Route.....

});

在這些路由的任何控制器中, Auth::user() 工作正常,並返回登錄的用戶實例。 到現在為止還挺好。

現在,我有另一組路由,它們是公開的,因此它們不使用auth:api中間件。 但是,登錄用戶也可以訪問這些路由,並且基於此條件(無論是否登錄),我想運行其他邏輯。 總而言之,登錄用戶和公共用戶都可以訪問該頁面; 但是如果用戶登錄了,我們會運行一個額外的邏輯。 但是,當我嘗試使用Auth::user()它返回 null,而auth()->check()返回 false。

請記住,我不能使用 auth 中間件,因為這會限制公共用戶訪問頁面,這不是我們所需要的。

如果用戶擁有需要驗證的信息,您可以在用戶請求路由時手動驗證該用戶。 如果他沒有,那么您可以對未經身份驗證的用戶使用您的邏輯。

https://laravel.com/docs/5.7/authentication#authenticating-users

這也可能有用

您應該將 auth 與警衛一起使用。

{{ \Auth::guard('api')->user(); }}

或者,您可以通過 Illuminate\\Http\\Request 實例訪問經過身份驗證的用戶。

說明

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}

檢查文檔

在調用Auth::guard('api')->user()工作時,我發現每次嘗試訪問經過身份驗證的用戶時都必須設置默認保護非常難看。

您可以做的是創建一個新的中間件,為特定路由設置默認保護。

創建一個新的中間件:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class DefaultGuard
{
    /**
     * The authentication factory instance.
     *
     * @var Auth
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param Auth $auth
     *
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param         $request
     * @param Closure $next
     * @param         $guard
     *
     * @return mixed
     */
    public function handle($request, Closure $next, $guard)
    {
        $this->auth->shouldUse($guard);

        return $next($request);
    }
}

將它添加到app\\Http\\Kernel.php$routeMiddleware屬性

protected $routeMiddleware = [
    'guard' => DefaultGuard::class,
];

將其應用於您的公共路線:

Route::group([ 'middleware' => 'guard:api'], function () {
    // Route.....
});

現在您可以像往常一樣訪問經過身份驗證的用戶,例如:

Auth::user();
$request->user();
etc.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM