CodeIgniter JWT

Bước 1 : Setup Project
1.1 Download CodeIgniter
Đầu tiên các bạn download CodeIgniter.Ở đây mình dùng version 3 download
Sau khi giải nén các bạn đổi tên folder root thành codeigniter_jwt nhé
1.2 Cấu hình .htaccess
Cấu hình file config

// codeigniter_jwt\application\config\config.php
$config['base_url'] = 'http://localhost/codeigniter_jwt/';
$config['index_page'] = '';

Tạo file .htaccess ở folder root

<IfModule mod_php5.c>
    php_value always_populate_raw_post_data -1
</IfModule>
RewriteEngine On
RewriteBase /codeigniter_jwt
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L,QSA]

Bước 2: Tạo database
Tạo database tên là codeigniter_jwt
Connect database:

//config/database.php
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'codeigniter_jwt',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

Tạo table users

CREATE TABLE `users` (
	`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
	`email` VARCHAR(250) NOT NULL COLLATE 'utf8_general_ci',
	`password` VARCHAR(150) NOT NULL DEFAULT '' COLLATE 'utf8_general_ci',
	`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	`updated_at` DATETIME NULL DEFAULT '0000-00-00 00:00:00',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB

Edit config/autoload.php

$autoload['libraries'] = array('database');

Bước 2: Setup JWT
Cải đặt:

composer require firebase/php-jwt

Tạo file models/User.php

Tao file controllers/Users.php

Chú ý:Tạo secret key

private $secret = "This is a secret key";

Bước 3:Test với postman
Link đang ký http://localhost/codeigniter_jwt/users/register

Link lấy token:http://localhost/codeigniter_jwt/users/login

Check token:Authorization
Link:http://localhost/codeigniter_jwt/users/check_token

Test get info one user with token key:
Link:http://localhost/codeigniter_jwt/users/detail_user/1

Link code here

Leave a Reply

avatar
  Subscribe  
Notify of