如何在 Codeigniter 3 REST 中进行令牌认证 API
How to make token authentication in Codeigniter 3 REST API
所以我刚刚在 Codeigniter 3 中制作完 REST API,我想用令牌进行身份验证,所以我使用了这个 repo https://github.com/ParitoshVaidya/CodeIgniter-JWT-Sample/tree/CI3
中的 JWT
我的问题是,如何让我的 API 控制器在每次请求时都需要令牌?
这是我的 api 控制器
function __construct($config = 'rest') {
parent::__construct($config);
$this->load->helper(array('text','url'));
$this->load->model('Api_model');
}
// GET ARTICLE
function index_get(){
$data = $this->Api_model->get_all_article();
return $this->response($data,200);
}
这是我的令牌控制器
public function token_get()
{
$tokenData = array();
$tokenData['id'] = 1;
$output['token'] = AUTHORIZATION::generateToken($tokenData);
$this->set_response($output, REST_Controller::HTTP_OK);
}
我建议将令牌逻辑移动到库中。然后,您将在所有控制器中使用它,而不必在 api 控制器中对控制器进行脏实例化。
添加classapplication\libraries\Token.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Token {
public function token_get()
{
$tokenData = array();
$tokenData['id'] = 1;
$output['token'] = AUTHORIZATION::generateToken($tokenData);
$this->set_response($output, REST_Controller::HTTP_OK); // <--
}
}
您必须在您的图书馆中提供此 REST_Controller
或相应地更改此逻辑。
然后在你的 APIController:
function token_get(){
$this->load->library('Token');
return $this->Token->token_get();
}
// GET ARTICLE
function index_get(){
$token = $this->token_get(); // added this line
$data = $this->Api_model->get_all_article();
return $this->response($data,200);
}
阅读更多关于 Libraries in CodeIgniter
所以我刚刚在 Codeigniter 3 中制作完 REST API,我想用令牌进行身份验证,所以我使用了这个 repo https://github.com/ParitoshVaidya/CodeIgniter-JWT-Sample/tree/CI3
中的 JWT
我的问题是,如何让我的 API 控制器在每次请求时都需要令牌?
这是我的 api 控制器
function __construct($config = 'rest') {
parent::__construct($config);
$this->load->helper(array('text','url'));
$this->load->model('Api_model');
}
// GET ARTICLE
function index_get(){
$data = $this->Api_model->get_all_article();
return $this->response($data,200);
}
这是我的令牌控制器
public function token_get()
{
$tokenData = array();
$tokenData['id'] = 1;
$output['token'] = AUTHORIZATION::generateToken($tokenData);
$this->set_response($output, REST_Controller::HTTP_OK);
}
我建议将令牌逻辑移动到库中。然后,您将在所有控制器中使用它,而不必在 api 控制器中对控制器进行脏实例化。
添加classapplication\libraries\Token.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Token {
public function token_get()
{
$tokenData = array();
$tokenData['id'] = 1;
$output['token'] = AUTHORIZATION::generateToken($tokenData);
$this->set_response($output, REST_Controller::HTTP_OK); // <--
}
}
您必须在您的图书馆中提供此 REST_Controller
或相应地更改此逻辑。
然后在你的 APIController:
function token_get(){
$this->load->library('Token');
return $this->Token->token_get();
}
// GET ARTICLE
function index_get(){
$token = $this->token_get(); // added this line
$data = $this->Api_model->get_all_article();
return $this->response($data,200);
}
阅读更多关于 Libraries in CodeIgniter