PHP code example of borisguery / oauth2-server

1. Go to this page and download the library: Download borisguery/oauth2-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

borisguery / oauth2-server example snippets

 php
class OAuht2Controller {

    public function tokenAction(Request $request)
    {
        $sfPasswordGrantType = new SymfonySecurityPasswordGrantType(
            $this->container->get('security.user_provider'),
            $this->container->get('security.encoder_factory')->getEncoder(UserAccount::class)
        );

        $clientStorage = new InMemoryClientStorage();
        $defaultClient = new Client(
            'test',
            null,
            [],
            ['password']
        );

        $clientStorage->save($defaultClient);

        $configuration = (new ResourceServerConfigurationBuilder())
            ->setAccessTokenStorage(new InMemoryAccessTokenStorage())
            ->setClientStorage($clientStorage)
            ->setRefreshStorage(new InMemoryRefreshTokenStorage())
            ->setAccessTokenGenerator(new Php7CSPRNGStringGenerator())
            ->addGrantType($sfPasswordGrantType)
            ->alwaysRequireAClient(true)
            ->alwaysGenerateARefreshToken(true)
            ->build()
            ->getResourceConfiguration()
        ;

        $resourceServer = new ResourceServer($configuration);

        $inputDataBag = SymfonyHttpFoundationRequestInputDataBagFactory::fromRequest($request);

        $attemptResult = $resourceServer->requestAccessToken(
            new TokenRequestAttempt($inputDataBag->getGrantType(), $inputDataBag)
        );

        if ($attemptResult instanceof SuccessfulTokenRequestAttemptResult) {
            $statusCode = 200;
            $response = [
                'access_token' => $attemptResult->getAccessToken()->getToken(),
                'expires_in'   => $attemptResult->getAccessToken()->getExpiresIn(),
                'token_type'   => $attemptResult->getAccessToken()->getTokenType(),
                'refresh_token' => $attemptResult->getRefreshToken()
                    ? $attemptResult->getRefreshToken()->getToken()
                    : null,
            ];
        } elseif ($attemptResult instanceof FailedTokenRequestAttemptResult) {
            $statusCode = 400;
            $response = [
                'error' => (string) $attemptResult->getGrantDecision()->getError(),
                'error_description' => $attemptResult->getGrantDecision()->getError()->getErrorDescription(),
                'error_uri' => $attemptResult->getGrantDecision()->getError()->getErrorUri(),
            ];
        }

        return new Response(json_encode($response), $statusCode, ['Content-Type' => 'application/json']);
    }
}