Estoy tratando de construir una API tranquila en codeigniter usando el servidor de descanso de Phil Sturgeon
El problema es que no puedo descifrar cómo hacer una autenticación basada en token. Estoy creando esa API para la aplicación móvil y es a través de HTTPS. Al principio, el usuario se autenticará al iniciar sesión y luego podrá usar las funcionalidades de la aplicación. Quiero implementar de la manera que se explica aquí: Cómo funciona la autenticación basada en token
Preguntas:
Si envío un token al servidor en la solicitud, ¿dónde debo verificar la validez?
¿La biblioteca del servidor de descanso admite la autenticación basada en token?
Si es así, ¿qué configuraciones debo hacer? o necesito implementar mis métodos de autenticación?
¿O hay una forma mejor/más sencilla de autenticación en lugar de basada en token?
No es compatible con la autenticación de token. Aquí están las modificaciones que hice para agregarlo. REST_Controller.php busque "switch ($rest_auth) {" y agregue este caso:
case 'token': $this->_check_token(); break;Luego agrega esta función:
/** Check to see if the user is logged in with a token * @access protected */ protected function _check_token () { if (!empty($this->_args[$this->config->item('rest_token_name')]) && $row = $this->rest->db->where('token', $this->_args[$this->config->item('rest_token_name')])->get($this->config->item('rest_tokens_table'))->row()) { $this->api_token = $row; } else { $this->response([ $this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized') ], self::HTTP_UNAUTHORIZED); } }config/rest.php
// *** Tokens *** /* Default table schema: * CREATE TABLE `api_tokens` ( `api_token_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `token` VARCHAR(50) NOT NULL, `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`api_token_id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB */ $config['rest_token_name'] = 'X-Auth-Token'; $config['rest_tokens_table'] = 'api_tokens';Controlador para obtener el token:
Construí un resto de controladores para obtener el token.
require APPPATH . 'libraries/REST_Controller.php'; class Token extends REST_Controller { /** * @response array */ public function index_get() { $data = $this->Api_model->create_token($this->api_customer_id); // ***** Response ****** $http_code = $data['http_code']; unset($data['http_code']); $this->response($data, $http_code); } }Función en modelo para token:
/** Creates a new token * @param type $in * @return type */ function create_token ($customer_id) { $this->load->database(); // ***** Generate Token ***** $char = "bcdfghjkmnpqrstvzBCDFGHJKLMNPQRSTVWXZaeiouyAEIOUY!@#%"; $token = ''; for ($i = 0; $i < 47; $i++) $token .= $char[(rand() % strlen($char))]; // ***** Insert into Database ***** $sql = "INSERT INTO api_tokens SET `token` = ?, customer_id = ?;"; $this->db->query($sql, [$token, $customer_id]; return array('http_code' => 200, 'token' => $token); }