oauth2 mechanism of laravel passport -- Interpretation of source code

If you have understood the principle of oauth2.0, you can also install the rear laravel passport. Now look at the relevant logic flow from the source code and how to go.
Before that, let's take a look at how laravel determines whether the http client request is a normal request or a json request, because the passport is requested by api json by default.
\vendor\laravel\framework\src\Illuminate\Http\Concerns\InteractsWithContentTypes.php determines whether the Accept of http header has json or + json.

 public function expectsJson()
    {
        return ($this->ajax() && ! $this->pjax() && $this->acceptsAnyContentType()) || $this->wantsJson();
    }

public function wantsJson()
    {
        $acceptable = $this->getAcceptableContentTypes();

        return isset($acceptable[0]) && Str::contains($acceptable[0], ['/json', '+json']);
    }

After knowing the request method, let's see how to obtain oauth access_token. You can view this record with PHP artist route: list

 POST| oauth/token| passport.token|Laravel\Passport\Http\Controllers\AccessTokenController@issueToken 

Later, enter the code view, \ vendor\laravel\passport\src\Http\Controllers\AccessTokenController.php, and then enter the respondToAccessTokenRequest method, which is in the figure library. Yes, the verification method of passport is to reference the oauth2 server of league.

public function issueToken(ServerRequestInterface $request)
    {
        return $this->withErrorHandling(function () use ($request) {
            return $this->convertResponse(
                $this->server->respondToAccessTokenRequest($request, new Psr7Response) 
            );
        });
    }

Now let's go in and have a look at vendor \ League \ oauth2 server \ SRC \ authorizationserver. PHP

public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response)
    {
        foreach ($this->enabledGrantTypes as $grantType) {
           //print_r($grantType);exit;
            if (!$grantType->canRespondToAccessTokenRequest($request)) {
                continue;
            }
            $tokenResponse = $grantType->respondToAccessTokenRequest(
                $request,
                $this->getResponseType(),
                $this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
            );

            if ($tokenResponse instanceof ResponseTypeInterface) {
                return $tokenResponse->generateHttpResponse($response);
            }
        }

        throw OAuthServerException::unsupportedGrantType();
    }

Read it here

  • Circular grant form (authorization code mode, simplified mode, password mode, client mode)
  • Generate access according to the grant type requested by the user_ Toekn operation, if not, continue
  • respondToAccessTokenRequest is an interface, which is implemented in different grant forms. This example uses password (\ vendor \ League \ oauth2 server \ SRC \ grant \ passwordgrant. PHP)
  • Generate a token and return it directly. Throw an exception if there is a problem

Let's go to PasswordGrant again

public function respondToAccessTokenRequest(
        ServerRequestInterface $request,
        ResponseTypeInterface $responseType,
        DateInterval $accessTokenTTL
    ) {
        // Validate request
        $client = $this->validateClient($request);
        $scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
        $user = $this->validateUser($request, $client);

        // Finalize the requested scopes
        $finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());

        // Issue and persist new access token
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
        $this->getEmitter()->emit(new RequestAccessTokenEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request, $accessToken));
        $responseType->setAccessToken($accessToken);

        // Issue and persist new refresh token if given
        $refreshToken = $this->issueRefreshToken($accessToken);

        if ($refreshToken !== null) {
            $this->getEmitter()->emit(new RequestRefreshTokenEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request, $refreshToken));
            $responseType->setRefreshToken($refreshToken);
        }

        return $responseType;
    }

The focus here is on the three verifications, namely, the overall client data format verification, followed by oauth scope permission verification, followed by database user verification according to account and password

$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$user = $this->validateUser($request, $client);

Until now, we have generated access for the entire oauth2 of laravel passport_ The core logic code flow of token has been completed. Let's see later that in the middleware, they judge the legitimacy of the token
In routes.php, you can see that the middleware is auth:api

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

The file vendor \ laravel \ framework \ SRC \ illuminate \ auth \ middleware \ authenticate.php authenticates. The parameter grads receives the api parameter, which will become the passport of auth.php under config to decrypt and verify. This logic is in the method \ vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php guard()

protected function authenticate($request, array $guards)
    {
        if (empty($guards)) {
            $guards = [null];
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        $this->unauthenticated($request, $guards);
    }

Here is the whole process from generation to verification of passport oauth2.

reference resources
https://www.cntofu.com/book/107/Laravel%20Passport%E2%80%94%E2%80%94OAuth2%20API%20%E8%AE%A4%E8%AF%81%E7%B3%BB%E7%BB%9F%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%88%E4%B8%8B%EF%BC%89.md

Keywords: PHP Laravel

Added by veeraa2003 on Sat, 06 Nov 2021 02:00:08 +0200