0

如果在授权标头中找不到它,我特别试图让 Sanctum 的 Guard 类在 JSON 请求正文中查找 API 令牌。我只需要在检查承载令牌后添加一个 elseif。

所以问题是:在不触及原始 Sanctum 文件的情况下,用我自己的方法(或类)覆盖此方法(或类)的最佳方法是什么?

<?php

namespace Laravel\Sanctum;

use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;

class Guard
{
    /**
     * The authentication factory implementation.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * The number of minutes tokens should be allowed to remain valid.
     *
     * @var int
     */
    protected $expiration;

    /**
     * Create a new guard instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @param  int  $expiration
     * @return void
     */
    public function __construct(AuthFactory $auth, $expiration = null)
    {
        $this->auth = $auth;
        $this->expiration = $expiration;
    }

    /**
     * Retrieve the authenticated user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function __invoke(Request $request)
    {
        if ($user = $this->auth->guard('web')->user()) {
            return $this->supportsTokens($user)
                        ? $user->withAccessToken(new TransientToken)
                        : $user;
        }

        if ($token = $request->bearerToken()) {
            $model = Sanctum::$personalAccessTokenModel;

            $accessToken = $model::where('token', hash('sha256', $token))->first();

            if (! $accessToken ||
                ($this->expiration &&
                 $accessToken->created_at->lte(now()->subMinutes($this->expiration)))) {
                return;
            }

            return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken(
                tap($accessToken->forceFill(['last_used_at' => now()]))->save()
            ) : null;
        }
    }

    /**
     * Determine if the tokenable model supports API tokens.
     *
     * @param  mixed  $tokenable
     * @return bool
     */
    protected function supportsTokens($tokenable = null)
    {
        return in_array(HasApiTokens::class, class_uses_recursive(
            $tokenable ? get_class($tokenable) : null
        ));
    }
}
4

1 回答 1

1

我不知道您是否已经想通了,但我认为您需要在 AppServiceProvider 引导方法中添加一个条目,并覆盖第94行的 SanctumServiceProvider 中的 configureGuard 功能。

app/Providers/AppServiceProvider.php

Auth::resolved(function ($auth) {
        $auth->extend('sanctum', function ($app, $name, array $config) use ($auth) {
            return tap($this->createGuard($auth, $config), function ($guard) {
                $this->app->refresh('request', $guard, 'setRequest');
            });
        });
    });

您还需要覆盖createGuard函数以使用您需要的功能指定您的自定义 Guard 类。

于 2020-06-15T06:36:32.953 回答