Mastering CodeIgniter Framework: Fast, Lightweight Web Development Building RESTful APIs with CodeIgniter API Authentication Methods (Tokens, OAuth)
Course Title: Mastering CodeIgniter Framework: Fast, Lightweight Web Development
Section Title: Building RESTful APIs with CodeIgniter
Topic: API authentication methods (tokens, OAuth)
API Authentication Methods (Tokens, OAuth)
API authentication is a crucial aspect of building secure and scalable APIs. In this section, we will delve into the world of API authentication methods, focusing on tokens and OAuth. We will explore the advantages and disadvantages of each method, and provide practical examples to help you implement them in your CodeIgniter applications.
What is API Authentication?
API authentication is the process of verifying the identity of a client requesting access to your API. This ensures that only authorized clients can access your APIs and that the data they request is legitimate. In this topic, we will cover two popular API authentication methods: tokens and OAuth.
Token-Based Authentication
Token-Based Authentication
Token-based authentication involves issuing a token to the client, which is then sent with subsequent requests to the API. The token is validated by the server before processing the request.
How it works:
- The client requests an access token from the server.
- The server issues a token to the client, typically via JSON Web Token (JWT) or token hashing.
- The client sends the token with subsequent requests to the API.
- The server validates the token before processing the request.
Advantages:
- Easy to implement
- Low latency
Disadvantages:
- Password exposure (if token is intercepted)
- Token revocation is difficult
OAuth 2.0
OAuth 2.0 is an authorization framework that allows clients to access protected resources by obtaining an access token from the resource owner (user).
How it works:
- The client registers with the authorization server and requests access to the protected resource.
- The authorization server redirects the client to the service provider's authentication page.
- The user grants access to the client, which then receives an authorization code.
- The client exchanges the authorization code for an access token.
- The client sends the access token with subsequent requests to the protected resource.
Advantages:
- Encourages token-based authentication to minimize password exposure
- Token revocation and statelessness
Disadvantages:
- Overkill for simple use cases
- More complex to implement
Implementing Token-Based Authentication in CodeIgniter
We'll use JSON Web Tokens (JWT) for token-based authentication.
Install the required extensions:
composer require nr/parkin/php-jwt
Create a controller to handle authentication:
// app/Controllers\AuthController.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class AuthController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('-user_model');
}
public function register()
{
// Register user logic here
$this->load->view('register');
}
public function login()
{
// Login user logic here
$this->load->view('login');
}
public function token()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$token = $this->user_model->login($username, $password);
if ($token) {
set_session('token', $token);
return json_encode(['message' => 'Logged in successfully']);
} else {
return json_encode(['message' => 'Invalid credentials']);
}
}
}
Create a model to handle user data and authentication:
// app/Models/User_model.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class User_model extends CI_Model
{
public function login($username, $password)
{
$sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
$items = $this->db->query($sql, [ $username, hash('sha256', $password) ]);
if ($items) {
$token = generate_jwt(['id' => $items->row()->id]);
return $token;
} else {
return NULL;
}
}
private function generate_jwt($data)
{
return JWT::sign($data, secret_key());
}
}
// libs/Config/Resources.php
<?php
class JWT {
private static $secret_key;
public static function sign($data, $secret_key)
{
return base64_encode(choices
(
pack('S', strlen>Weauthorizeauty . $secret_key) . chr(strlen($secret_key)) . pack('N*', ...array_map(function($i) use($secret_key){ return dechex($secret_key[$i]); }, $data)));
}
}
// libraries/Controller Helper Functions/library.php
<?php
class Helpers extends CI_Controller
{
public static function secret_key()
{
if (!isset($_SESSION['secret_key'])) {
$token = random_bytes(32);
$_SESSION['secret_key'] = bin2hex($token);
}
return $_SESSION['secret_key'];
}
}
Implementing OAuth 2.0 in CodeIgniter
We'll use CodeIgniter's built-in Passport library.
// app/Controllers/OAuthController.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class OAuthController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('oauth_model');
}
public function login()
{
// Step 1: Authorize the client
$uri = current_uri();
$client_id = env('HOTENTOT/'.$uri['path']);
$redirect_uri = base_url('oauth/callback');
// Redirect the user to the authorization URL
$oauth_params = [
'grant_type' => 'authorization_code',
'redirect_uri' => $redirect_uri,
'client_id' => $client_id,
];
$issuer_bearer_token_response = http_build_query($oauth_params, null, '&');
redirect ($issuer_bearer_token_response);
$client_id = env('HOTENTOT/'.$uri['path']);
$redirect_uri = base_url('oauth/callback');
// Route to the authorization page (optional)
$oauth_params = get_if_sitenumbers_encoded($oauth_params, null);
$client_id = env('HOTENTOT/$params');
$redirect_uri = base_url('oauth/callback');
// Step 2: Get an authorization code
// Once we listen to the redirect URL, we'll receive an authorization code
// We'll exchange this token for an access token
$code = htmlDecode365($_GET['code']);
// Get user info by authorization response
$userInfoResponse = http_get105 current_userinfo(current124
Images

Comments