PHP code example of friendsofhyperf / oauth2-server

1. Go to this page and download the library: Download friendsofhyperf/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/ */

    

friendsofhyperf / oauth2-server example snippets




declare(strict_types=1);
/**
 * This file is part of friendsofhyperf/components.
 *
 * @link     https://github.com/friendsofhyperf/components
 * @document https://github.com/friendsofhyperf/components/blob/main/README.md
 * @contact  [email protected]
 */
use FriendsOfHyperf\Oauth2\Server\Enums\EncryptionKeyType;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;

use function Hyperf\Support\env;

return [
    'authorization_server' => [
        # Full path to the private key file.
        # How to generate a private key: https://oauth2.thephpleague.com/installation/#generating-public-and-private-keys
        'private_key' => env('OAUTH2_PRIVATE_KEY'),
        # Passphrase of the private key, if any
        'private_key_passphrase' => env('OAUTH2_PRIVATE_KEY_PASSPHRASE'),
        # The plain string or the ascii safe string used to create a Defuse\Crypto\Key to be used as an encryption key.
        # How to generate an encryption key: https://oauth2.thephpleague.com/installation/#string-password
        'encryption_key' => env('OAUTH2_ENCRYPTION_KEY'),
        # The encryption key type.
        'encryption_key_type' => EncryptionKeyType::from(env('OAUTH2_ENCRYPTION_KEY_TYPE', 'plain')),
        'response_type' => BearerTokenResponse::class,
        # Whether to revoke refresh tokens after they were used for all grant types (default to true)
        'revoke_refresh_tokens' => true,
        # How long the issued access token should be valid for.
        # The value should be a valid interval: http://ph
        'access_token_ttl' => new DateInterval('PT1H'),
        # How long the issued auth code should be valid for.
        # The value should be a valid interval: http://php.net/manual/en/dateinterval.construct.php#refsect1-dateinterval.construct-parameters
        'auth_code_ttl' => new DateInterval('PT10M'),
        # How long the issued refresh token should be valid for.
        # The value should be a valid interval: http://php.net/manual/en/dateinterval.construct.php#refsect1-dateinterval.construct-parameters
        'refresh_token_ttl' => new DateInterval('P1M'),
        # Whether to enable the client credentials grant
        'enable_client_credentials_grant' => true,
        # Whether to enable the password grant
        'enable_password_grant' => true,
        # Whether to enable the refresh token grant
        'enable_refresh_token_grant' => true,
        # Whether to enable the authorization code grant
        'enable_auth_code_grant' => true,
        'enable_implicit_grant' => false,
        # Whether to 

Router::addGroup('/api', function () {
    Router::get('user', [UserController::class, 'index'])->add(ResourceServerMiddleware::class);
});



use FriendsOfHyperf\Oauth2\Server\Factory\ResourceServerFactory;
use FriendsOfHyperf\Oauth2\Server\Model\AccessToken;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ServerRequestInterface;

class YourController
{
    #[Inject]
    private ResourceServerFactory $resourceServerFactory;

    public function getUserData(ServerRequestInterface $request)
    {
        // Build the resource server
        $resourceServer = $this->resourceServerFactory->build();
        
        // Validate the access token
        $accessToken = $resourceServer->validateAuthenticatedRequest($request);
        
        // Get the token ID
        $tokenId = $accessToken->getAttribute('oauth_access_token_id');
        
        // You can now use the token ID to fetch more information from your database
        // $accessTokenModel = AccessToken::find($tokenId);
        
        // Return protected data
        return ['user_id' => $accessToken->getAttribute('oauth_user_id')];
    }
}



use FriendsOfHyperf\Oauth2\Server\Factory\AuthorizationServerFactory;
use Hyperf\Di\Annotation\Inject;

class YourController
{
    #[Inject]
    private AuthorizationServerFactory $authorizationServerFactory;

    public function handleTokenRequest()
    {
        // Build the authorization server
        $authorizationServer = $this->authorizationServerFactory->build();
        
        // Use the authorization server for token validation, etc.
        // ...
    }
}
bash
php bin/hyperf.php vendor:publish friendsofhyperf/oauth2-server
bash
# Generate private/public key pair
php bin/hyperf.php oauth2-server:generate-keypair
bash
php bin/hyperf.php migrate
bash
php bin/hyperf.php oauth2-server:create-client \
    --name="My App" \
    --redirect-uri="https://myapp.com/callback" \
    --grant-type="authorization_code" \
    --grant-type="password" \
    --grant-type="refresh_token"