Skip to content

Releases: bertugfahriozer/ci4oauth2

v1.x

27 Oct 12:04
Compare
Choose a tag to compare

Codeigniter 4 OAuth2 Library

This is an OAuth2 library for use with CodeIgniter 4. It allows users to authorize and authenticate with third-party applications.

Features

  • Easily configure and deploy an OAuth2 server application.
  • Support for authorizing and authenticating with third-party applications for users.
  • Integration with any client application that supports the OAuth2 protocol.
  • Access authorization mechanisms to secure users' abilities.

Installation

To add the library to your project, follow these steps:

  1. Navigate to your project files.

  2. Use Composer to add the library to your project with the following command:

    composer require bertugfahriozer/ci4oauth2

  3. To create the required database tables, run the following command:

    php spark migrate -all

  4. You will need to create a configuration file. Run the following command to generate a config file:

    php spark make:config

The OAuth2 library is now ready to use in your project!

Usage

Adding a Filter

We'll include the initial filter. The file to be included is "application/Config/Filter.php".

<?php namespace App\Config;

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

URI Routing

In this section, an example URI structure to be added to the "App/Config/Routes.php" file is provided.

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

Example Usage

Below is a simple example of using the library:

<?php

namespace App\Controllers;

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

class AuthController extends Controller {
    // ...
}

You can extend these example methods to create users in the database and use different authorization types based on your project's requirements.

Example Folder

You can copy and test the code found in this folder after including the library. The example folder path is "ci4oauth2/example".

Authorization Types

  • Authorization Code: Used when an application wants to access protected resources on behalf of a user (i.e., a 3rd party user). Example Request

  • Client Credentials: Used when an application wants to access protected resources under its control (i.e., no third-party). Example Request

  • User Credentials (Password): Used when a user has a trusted relationship with the client and can provide credentials directly. Example Request

  • Refresh Token: Used to obtain additional access tokens to extend the user's access rights. Example Request

  • JWT Bearer (JWT Bearer Token): Used when the application wants to obtain access tokens without transmitting sensitive information. Example Request

Contribution

If you have any issues or feature requests related to this library on GitHub, please report them using the GitHub issue tracker. If you'd like to contribute to the project, please submit a pull request.

License

This library is licensed under the MIT License.

Full Changelog: 0.5.1...1.1.3

v0.x

21 Oct 16:28
Compare
Choose a tag to compare
v0.x Pre-release
Pre-release
English Türkçe

Codeigniter 4 OAuth2 Library

This is an OAuth2 library that can be used in CodeIgniter 4. It allows users to authorize and authenticate with
third-party applications.

Features

  • Easily configure and deploy an OAuth2 server application.
  • Support for authorizing and authenticating users with third-party applications.
  • Integration with any client application that supports the OAuth2 protocol.
  • Access authorization mechanisms that secure user capabilities.

Installation

To add the library to your project, follow these steps:

  1. Navigate to your project's files.

  2. Use Composer to add the library to your project with the following command:

    composer require bertugfahriozer/ci4oauth2

  3. To create the required database tables, run the following command:

  4. php spark migrate -all

  5. You'll need to create a configuration file. To create a config file, run the following command:

    php spark make:config

  6. You're now ready to use the OAuth2 library in your project!

Usage

Configuration

Here's an example of a configuration file you can create for your OAuth2 library:

<?php namespace App\Config

class Oauth2Conf extends BaseConfig
{
   public $config = [
      'always_issue_new_refresh_token' => true,
      'refresh_token_lifetime' => 2592000
   ];
}

The example above is a sample config file created for the Refresh Token method.

Usage example of the OAuth2 library:

<?php

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());
    }
}

Here are sample methods for creating users in the database:

public function createclient() {
   $vald = [
      'client_id' => ['label' => '', 'rules' => 'required'],
      'client_secret' => ['label' => '', 'rules' => 'required'],
      'redirect_url' => ['label' => '', 'rules' => 'required|valid_url'],
      'grant_types' => ['label' => '', 'rules' => 'required'],
   ];
   if (strpos($this->request->getPost('grant_types'), "password")) {
      $vald['username'] = ['label' => '', 'rules' => 'required'];
      $vald['password'] = ['label' => '', 'rules' => 'required'];
   }
   $valData = ($vald);
   if ($this->validate($valData) == false) return $this->failValidationErrors($this->validator->getErrors());
   $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' => 'required'],
      'password' => ['label' => '', 'rules' => 'required']
   ]);
   if ($this->validate($valData) == false) return $this->failValidationErrors($this->validator->getErrors());
   $oauth = new \ci4oauth2\Libraries\OauthPdoStorage();
   $result = $oauth->setUser($this->request->getPost('username'), $this->request->getPost('password'));
   if ($result === 0) return $this->respondCreated(['result' => 'user created']);
   else if ($result === true) return $this->respondUpdated(['result' => 'user updated.']);
   else return $this->failServerError();
}

Authorization Types

Authorization Code

The authorization code grant type is used when the client wants to request access to protected resources on behalf of
another user (i.e., a third-party user). This is the most commonly associated data type with
OAuth. RFC 6749

Example Request

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'

Result

{ "access_token": "794b60b710a9d9128387d1dc7920484cf32080c6", "expires_in": 3600, "token_type": "Bearer", "scope": null, "refresh_token": "fa7f4a30f7861047a9a3c130d197b8d708bc0fa3" }

Client Credentials

The Client Credentials grant type is used when the client is requesting access to protected resources under its
control (i.e. there is no third party). RFC 6749

Example Request

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'

Result

{ "access_token": "33d85a1a68ad617add7f66cd7855e532738c3d84", "expires_in": 3600, "token_type": "Bearer", "scope": null }

User Credentials

The User Credentials grant type (also known as Resource Owner Password Credentials) is used when the user has a trusted
relationship with the client, and so can supply credentials
directly. RFC 6749

Example Request

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'

Result

{ "access_token": "557118343a9f7642804cdeef124195be437eb9c2", "expires_in": 3600, "token_type": "Bearer", "scope": null, "refresh_token": "308c5f9b3b91cdc233b64550e13baa287efa3eea" }

Refresh Token

The Refresh Token grant type is used to obtain additional access tokens in order to prolong the client's authorization
of a user's resources. RFC 6749

Example Request

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'

Result

{ "access_token": "7e0c0ed74a06f21c5c0e3d75a086f6c7306113b2", "expires_in": 3600, "token_type": "Bearer", "scope": null }

JWT Bearer

The JWT Bearer grant type is used when the client wants to receive access tokens without transmitting sensitive
information such as the client secret. This can also be used with trusted clients to gain access to user resources
without user authorization. RFC 7523

JWT Preparation

To prepare JWTs, SSL keys should be created in advance and shared with the server where the requests will be made, or a
panel should be set up to process the data. Here's an example of creating an SSL:

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

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

A code example to generate a JWT:

/**
* 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 ...
Read more