PHP code example of bertugfahriozer / ci4oauth2

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

    

bertugfahriozer / ci4oauth2 example snippets




namespace Config;

use CodeIgniter\Config\BaseConfig;

class Oauth2Conf extends BaseConfig
{
    public array $tables = ['client_table' => 'oauth_clients',
        'access_token_table' => 'oauth_access_tokens',
        'refresh_token_table' => 'oauth_refresh_tokens',
        'code_table' => 'oauth_authorization_codes',
        'user_table' => 'oauth_users',
        'jwt_table' => 'oauth_jwt',
        'jti_table' => 'oauth_jti',
        'scope_table' => 'oauth_scopes',
        'public_key_table' => 'oauth_public_keys'];

    public array $jwtConf=[
        'aud'=> 'https://oauth' // you must edit here
    ];

    public int $oauthFilterCap = 60;
    public int $rateLimitCap = 2;

    /* --------------------------------------------------------------------
     * Encryption Algorithm to use
     * --------------------------------------------------------------------
     * Valid values are
     * - PASSWORD_DEFAULT (default)
     * - PASSWORD_BCRYPT
     * - PASSWORD_ARGON2I  - As of PHP 7.2 only if compiled with support for it
     * - PASSWORD_ARGON2ID - As of PHP 7.3 only if compiled with support for it
     *
     * If you choose to use any ARGON algorithm, then you might want to
     * uncomment the "ARGON2i/D Algorithm" options to suit your needs
     */
    public $hashAlgorithm = PASSWORD_DEFAULT;
    public array $phpHashConfig = [
        'hashMemoryCost' => 2048,
        'hashTimeCost' => 4,
        'hashThreads' => 4,
        'hashCost' => 10
    ];
}

 namespace Config

class Filters extends BaseConfig
{
    public array $aliases = [
        ...
        'oauthfilter' => \ci4oauth2\Filters\OauthFilter::class,
        'rateLimit' => \ci4oauth2\Filters\RateLimit::class
    ];
    
    ...
    public array $filters = [
        'rateLimit' => ['before' => ['login', 'createclient', 'createuser', 'genjwt', 'token']],
        'oauthfilter' => ['before' => ['api','api/*']]
    ];
}

$routes->group('api', ['namespace' => 'App\Controllers'], static function ($routes) {
    $routes->resource('blog',['only'=>['index','show','create', 'update', 'delete']]);
});



namespace App\Controllers;

use CodeIgniter\Controller;
use ci4oauth2\Libraries\Oauth;

class AuthController extends Controller {
private $oauth;
private $respond;

    public function __construct() {
        $config = config('Oauth2Conf');

        $oauth = new Oauth($this->request->getPost('grant_type'), $config);
        $this->respond = $oauth->server->handleTokenRequest($req);
    }

    public function authorize() {
        return $this->respond(json_decode($this->respond->getResponseBody()), $this->respond->getStatusCode());
    }
}

public function createclient() {
   $vald = [
      'client_id' => ['label' => '', 'rules' => 'el' => '', 'rules' => 'es'), "password")) {
      $vald['username'] = ['label' => '', 'rules' => 'tErrors());
   $oauth = new \ci4oauth2\Libraries\OauthPdoStorage();
   $result = $oauth->setClientDetails($this->request->getPost('client_id'), $this->request->getPost('client_secret'), $this->request->getPost('redirect_url'), $this->request->getPost('grant_types'));
   if ($result === 0) return $this->respondCreated(['result' => 'client created']);
   else if ($result === true) return $this->respondUpdated(['result' => 'client updated.']);
   else return $this->failServerError();
}

public function createuser() {
   $valData = ([
      'username' => ['label' => '', 'rules' => '

/**
* Generate a JWT
*
* @param $privateKey The private key to use to sign the token
* @param $iss The issuer, usually the client_id
* @param $sub The subject, usually a user_id
* @param $aud The audience, usually the URI for the oauth server
* @param $exp The expiration date. If the current time is greater than the exp, the JWT is invalid
* @param $nbf The "not before" time. If the current time is less than the nbf, the JWT is invalid
* @param $jti The "jwt token identifier", or nonce for this JWT
*
* @return string
  */
  function generateJWT($privateKey, $iss, $sub, $aud, $exp = null, $nbf = null, $jti = null) {
     if (!$exp) {
        $exp = time() + 1000;
     }
   
     $params = array(
        'iss' => $iss,
        'sub' => $sub,
        'aud' => $aud,
        'exp' => $exp,
        'iat' => time(),
     );
   
     if ($nbf) {
        $params['nbf'] = $nbf;
     }
   
     if ($jti) {
        $params['jti'] = $jti;
     }
   
     $jwtUtil = new OAuth2\Encryption\Jwt();
   
     return $jwtUtil->encode($params, $privateKey, 'RS256');
  }

   composer 

    php spark make:config
   

    php spark migrate -all
    



namespace Config;

use CodeIgniter\Config\BaseConfig;

class Oauth2Conf extends BaseConfig
{
    public array $tables = ['client_table' => 'oauth_clients',
        'access_token_table' => 'oauth_access_tokens',
        'refresh_token_table' => 'oauth_refresh_tokens',
        'code_table' => 'oauth_authorization_codes',
        'user_table' => 'oauth_users',
        'jwt_table' => 'oauth_jwt',
        'jti_table' => 'oauth_jti',
        'scope_table' => 'oauth_scopes',
        'public_key_table' => 'oauth_public_keys'];

    public array $jwtConf=[
        'aud'=> 'https://oauth' // you must edit here
    ];

    public int $oauthFilterCap = 60;
    public int $rateLimitCap = 2;

    /* --------------------------------------------------------------------
     * Encryption Algorithm to use
     * --------------------------------------------------------------------
     * Valid values are
     * - PASSWORD_DEFAULT (default)
     * - PASSWORD_BCRYPT
     * - PASSWORD_ARGON2I  - As of PHP 7.2 only if compiled with support for it
     * - PASSWORD_ARGON2ID - As of PHP 7.3 only if compiled with support for it
     *
     * If you choose to use any ARGON algorithm, then you might want to
     * uncomment the "ARGON2i/D Algorithm" options to suit your needs
     */
    public $hashAlgorithm = PASSWORD_DEFAULT;
    public array $phpHashConfig = [
        'hashMemoryCost' => 2048,
        'hashTimeCost' => 4,
        'hashThreads' => 4,
        'hashCost' => 10
    ];
}

 namespace Config

class Filters extends BaseConfig
{
    public array $aliases = [
        ...
        'oauthfilter' => \ci4oauth2\Filters\OauthFilter::class,
        'rateLimit' => \ci4oauth2\Filters\RateLimit::class
    ];
    
    ...
    public array $filters = [
        'rateLimit' => ['before' => ['login', 'createclient', 'createuser', 'genjwt', 'token']],
        'oauthfilter' => ['before' => ['api','api/*']]
    ];
}

$routes->group('api', ['namespace' => 'App\Controllers'], static function ($routes) {
    $routes->resource('blog',['only'=>['index','show','create', 'update', 'delete']]);
});



namespace App\Controllers;

use CodeIgniter\Controller;
use ci4oauth2\Libraries\Oauth;

class AuthController extends Controller
{
    private $oauth;
    private $respond;

    public function __construct()
    {
        $config = config('Oauth2Conf');

        $oauth = new Oauth($this->request->getPost('grant_type'),$config);
        $this->respond = $oauth->server->handleTokenRequest($req);
    }

    public function authorize()
    {
        return $this->respond(json_decode($this->respond->getResponseBody()), $this->respond->getStatusCode());
    }
}

public function createclient()
    {
        $vald = [
            'client_id' => ['label' => '', 'rules' => ' => '', 'rules' => '_types'), "password")) {
            $vald['username'] = ['label' => '', 'rules' => 'Errors());
        $oauth = new \ci4oauth2\Libraries\OauthPdoStorage();
        $result = $oauth->setClientDetails($this->request->getPost('client_id'), $this->request->getPost('client_secret'), $this->request->getPost('redirect_url'), $this->request->getPost('grant_types'));
        if ($result === 0) return $this->respondCreated(['result' => 'client created']);
        else if ($result === true) return $this->respondUpdated(['result' => 'client updated.']);
        else return $this->failServerError();
    }

    public function createuser()
    {
        $valData = ([
            'username' => ['label' => '', 'rules' => '

curl --location 'https://oauth/authorize' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=testclient' \
--data-urlencode 'redirect_uri=http://oauth/' \
--data-urlencode 'code=xyz' \
--data-urlencode 'client_secret=testpass'

curl --location 'https://oauth/authorize' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=testbertug' \
--data-urlencode 'client_secret=passbertug'

curl --location 'https://oauth/authorize' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=testbertug' \
--data-urlencode 'password=testpass' \
--data-urlencode 'client_id=testbertug' \
--data-urlencode 'client_secret=passbertug'

curl --location 'https://oauth/authorize' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'refresh_token=afd5ab42392fd24fe3dc8b0f88c4505b4841d64a' \
--data-urlencode 'client_id=testbertug' \
--data-urlencode 'client_secret=passbertug'

// private key
$ openssl genrsa -out privatekey.pem 2048

// public key
$ openssl rsa -in privkey.pem -pubout -out publickey.pem

/**
 * Generate a JWT
 *
 * @param $privateKey The private key to use to sign the token
 * @param $iss The issuer, usually the client_id
 * @param $sub The subject, usually a user_id
 * @param $aud The audience, usually the URI for the oauth server
 * @param $exp The expiration date. If the current time is greater than the exp, the JWT is invalid
 * @param $nbf The "not before" time. If the current time is less than the nbf, the JWT is invalid
 * @param $jti The "jwt token identifier", or nonce for this JWT
 *
 * @return string
 */
function generateJWT($privateKey, $iss, $sub, $aud, $exp = null, $nbf = null, $jti = null)
{
    if (!$exp) {
        $exp = time() + 1000;
    }

    $params = array(
        'iss' => $iss,
        'sub' => $sub,
        'aud' => $aud,
        'exp' => $exp,
        'iat' => time(),
    );

    if ($nbf) {
        $params['nbf'] = $nbf;
    }

    if ($jti) {
        $params['jti'] = $jti;
    }

    $jwtUtil = new OAuth2\Encryption\Jwt();

    return $jwtUtil->encode($params, $privateKey, 'RS256');
}

curl --location 'http://oauth/authorize' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer' \
--data-urlencode 'assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ0ZXN0Y2xpZW50Iiwic3ViIjoiYmVydHVnIiwiYXVkIjoiaHR0cHM6XC9cL29hdXRoXC90b2tlbiIsImV4cCI6MTY5Nzk0MzA0NywiaWF0IjoxNjk3OTQyMDQ3fQ.zOAR0P4M1MUfNC3Ptn_yuu3YJEwkTl503_RFCGU3omd2HNc12NAWxlZ9hXFr4-T5ymfizWix1hwNcqnBfyO69_ugsHK2G9x5zfzrTfr3cTk592LGWIE6zVhbr2ybmCStz_oocDqBrAO_aQcY0SMFOgqyQPb2OIx_z2rpBmCSdgpaiNB1f0eFbtwlFcbk_IQ9VjU-pvqVaOdWYCjUV690q3gztASBbqzRpqlEVvh9pSdHe700e5eGdefW4gept11VN9i8EL5JuiQJYT0ptOfQbzqJ3N534FLFn56Zg77D2i9yFsAckLZpyyKQCSM-G_-4Jjsamm0fuEANiRDK25PRPF82DRnTOoW09N4z6h5pmk82oibGsqpyjEEmVyT5_UVoAwvKmjvsEMp2L46BM9C4bAm5qdjk_GWZcH_mr98wmfbkNDZ6cPegMMoIVz13yUHBp3VFDYb0EpigqWj6-fBDOxn7__a9S2qIlD6n3Uhg5MxI5HmwB-mrCJ-_CJ2m0hETaW94-KzcN23BUgk5CAdUkwMfndtW8nCmd3MXObo2b_rK8bJlhl_XH87xeGGY7DVb8t1vQnEd0-aonN790qSIt3Bsuzsa7kNEo_YVIu14gcae_9vzN2qn_ZUbzs8xO9t8WEq28M6VdU0xtdnvcq9HobFnIwaRpgsrGTjSOciw2nU'