Laravel api 发送授权时获取 Auth::user() 的路由,但在您不发送授权时不会命中 401

Laravel api route that grabs Auth::user() when Authorization is sent, but doesn't hit 401 whenever you don't

所以现在我正在使用 Laravel 对 api 路由的默认身份验证:

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

唯一的问题是,如果未登录的用户访问该页面,它将抛出 401。

我想知道是否有一种方法可以在发送令牌后让用户登录,但如果没有,他们仍然可以点击 api。

我知道这很可能是自定义中间件,但我没有太多创建中间件的经验,所以我不确定从哪里开始

编辑

app/Http/Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * 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\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:1000,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Fruitcake\Cors\HandleCors::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'admin' => \App\Http\Middleware\IsAdmin::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'cors' => \Fruitcake\Cors\HandleCors::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

这是我的路线 api.php 文件的一个非常简化的版本 routes/api.php

<?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::group(['prefix' => 'v2', 'middleware' => ['cors:api']], function() {
    //routes that people need to be logged into to do
    Route::group(['middleware' => ['auth:api']], function() {
        Route::post('/comments/save/{type}/{id}', 'App\Http\Controllers\Api\v2\CommentController@save');

        Route::get('/leagues/{id}', 'App\Http\Controllers\Api\v2\LeaguesController@get');;
    });

    Route::post('/auth/login', 'App\Http\Controllers\Api\v2\AuthController@login');
    
    Route::post('/contact', 'App\Http\Controllers\Api\v2\ContactController@sendMessage');
});

基本上我希望能够使用已登录用户或未登录用户访问 /leagues/{id} 路由。如果用户已登录,则通过 Auth::user() 获取用户。如果它有帮助的话,我正在使用 React 作为前端并在授权 header 中发送一个 api_token 就像 Bearer $token.

我通过创建自己的自定义中间件找到了一种方法。对于任何感兴趣的人,这里是:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use App\Models\User;

class OptionalAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $header = $request->header('Authorization');
        if(!empty($header)){
            $token = str_replace('Bearer ', '', $header);
            $user = User::where('api_token', '=', $token)->first();
            if(!empty($user)){
                Auth::login($user);
            }
        }

        return $next($request);
    }
}