【问题标题】:Codeigniter web servicesCodeigniter 网络服务
【发布时间】:2012-03-14 04:37:27
【问题描述】:

我正在使用 Codeigniter 1.7。有没有人有使用 PHP 创建 Web 服务的经验,尤其是在 CodeIgniter 框架中?实施 Web 服务时需要考虑哪些安全措施?如何使用 API 密钥提供身份验证?

有什么想法吗?

【问题讨论】:

    标签: web-services codeigniter authentication soap


    【解决方案1】:

    这取决于您要查询的网络服务类型。例如,Web 服务会成为守护进程吗?或典型的在线网络服务。对于其中任何一个,您都必须实现 RESTful 类型。 RESTful 意味着无状态连接。这是使用 API 密钥的地方;例如,识别用户。

    幸运的是,Codeigniter 包含许多库和扩展。此类库的示例可以在这里:https://github.com/philsturgeon/codeigniter-restserver

    现在出于安全考虑:API 密钥将取代会话或任何状态。您必须对 api 进行全面检查。许多实施 API 的网站为相同的最终结果提供不同的解决方案。

    使用 API 密钥进行身份验证很简单。您可以根据存储类型(数据库)检查它。

    这是一个使用 codeigniter 和之前链接的库的教程:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

    这可能有点模糊,但由于您没有任何具体问题或明显需求,因此很难具体说明。

    编辑:

    在这种情况下,最好实现一个 RESTful 接口,这样您的 iphone 应用程序也可以使用您的服务提供的所有用户功能。最好的方法是以一种方式使所有东西都可以访问。这意味着 iphone 连接和 Web 连接没有不同的控制器/型号。

    例如,您可以拥有以下控制器:

    <?php
    
    class Auth extends CI_Controller{
    
        public function login(){
          //Check if their accessing using a RESTful interface;
          $restful = $this->rest->check();
          if($restful){
             //Check for the API keys;
             $apiKey    = $this->input->get('apiKey');
             $secretKey = $this->input->get('secretKey');
    
             //If you have any rules apon the keys you may check it (i.e. their lengths,                 
             //character restrictions, etc...)
             if(strlen($apiKey) == 10 and strlen($secretKey) == 14)
             {
               //Now check against the database if the keys are acceptable;
               $this->db->where('apiKey', $apiKey);
               $this->db->where('secretKey', $secretKey);
               $this->db->limit(1);
               $query = $this->db->get('keys');
               if($this->db->count_all_results() == 1)
               {
                 //It's accepted the keys now authenticate the user;
                 foreach ($query->result() as $row)
                 {
                    $user_id = $row->user_id;
                    //Now generate a response key;
                    $response_key = $this->somemodel->response_key($user_id);
                    //Now return the response key;
                    die(json_encode(   array(
                                             'response_key' => $response_key, 
                                             'user_id' => $user_id
                                       )
                                   )
                       );
    
                 } //End of Foreach
               }//End of Result Count
             }//End of length / character check;
          } else {
            //Perform your usual session login here...;
    
          }
       }
    }
    
    ?>
    

    现在这只是执行这些类型请求的一个小示例。这可以适用于任何类型的控制器。虽然这里有几个选项。您可以让每个请求都传递 apikey 和密钥,并在每个请求中验证它。或者,您可以拥有某种白名单,一旦您第一次通过验证,之后的每个请求都会被列入白名单,或者相反被列入黑名单。

    希望这会有所帮助, 丹尼尔

    【讨论】:

    • Thanx Daniel。我有一个 Web 应用程序。我想通过使用 Web 服务为我的应用程序实现移动应用程序(iphone)。那么你能建议我任何想法吗?
    【解决方案2】:
    <?php 
    //First Create Api file in controller name Api.php
    /*
    api call in postman
    login : 
        email , password
        http://localhost/demo/api/login
        https://prnt.sc/pbs2do
    register (user): : 
        fullname , email ,  password , recipeunit
        http://localhost/demo/api/signup
        https://prnt.sc/pbs3cc
    
    profile and list (user profile and all user ) : 
        View Profile : email, if all then pass blank  
    http://localhost/demo/api/userlist
    
    
    change password :  
        http://localhost/demo/api/change_password
        email ,password ,newpassword , conformnewpassword (if needed)
        https://prnt.sc/pbs3rt
    
    */
    
    if(!defined('BASEPATH')) exit('No direct script access allowed');
    
    require APPPATH . '/libraries/BaseController.php'; // this file will download first and pest in library
    
    class Api extends BaseController
    {
        /**
         * This is default constructor of the class
         */
        public function __construct()
        {
            parent::__construct();
           $this->load->model('api/signup_model','signup_model');
        }
    
        /**
         * Index Page for this controller.
         */
        public function index()
        {
    
        }
        public function signup() 
        {
            $this->signup_model->signup();
        }
        public function login()
        {
            $this->signup_model->login();
        }
        public function userlist()
        {
            $this->signup_model->userlist();
        }
        public function edit_user()
        {
            $this->signup_model->edit_user();
        }
        public function change_password()
        {
            $this->signup_model->change_password();
        }
        public function testpass()
        {
            $this->signup_model->testpass();
        }
    }
    
    // then create model in model folder create api folder create signup_model.php file 
    //after that
    
    
    if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    class Signup_model extends CI_Model {
    
        public function __construct() 
        {
            parent::__construct();
            $this->load->database(); /* load database library */
    
        }
        // User register (signin) process 
        public function signup($data = array())
        {
            // another db field update like dt_createddate  
            if(!array_key_exists('dt_createddate', $data)){
                $data['dt_createddate'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('dt_updateddate', $data)){
                $data['dt_updateddate'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('dt_updateddate', $data)){
                $data['dt_updateddate'] = date("Y-m-d H:i:s");
            }
            $data['var_fullname'] = $this->input->post('fullname');
            $data['var_email'] = $this->input->post('email');
            $data['var_password'] =getHashedPassword($this->input->post('password')) ;
    
            $data['int_recipeunit'] = $this->input->post('recipeunit');
           // if(!empty($data['var_fullname']) && !empty($data['var_email']) && !empty($data['var_password']) ){ }
    
            /* check emailid  all ready exist or not */
            $email_check=$this->input->post('email');
            $this->db->select('var_email');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email_check);
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {           
                echo "{\"status\" : \"404\",\"message\" : \"Email all ready register\",\"data\":".str_replace("<p>","",'{}'). "}";
            }
            else 
            {
                $insert = $this->db->insert('tbl_user', $data);
                if($insert){
                $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                $insert_id = $this->db->insert_id();
                $query = $this->db->get_where('tbl_user', array('int_id' => $insert_id));
                echo "{\"status\" : \"200\",\"message\" : \"User added sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                // return $this->db->insert_id();
    
                }else
                {
                    $message="Something Wrong";
                    echo "{\"status\" : \"400\",\"data\":".str_replace("<p>","",json_encode($message)). "}";
                    // return false;
                }
            }
    
        }
    
        /* Login user   $email, $password*/
        function login()
        {
            $email=$this->input->post('email');
            $password=$this->input->post('password');
            $this->db->select('int_id,var_email,var_password');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email);
            $this->db->where('chr_status', 'A');
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {
                if(verifyHashedPassword($password, $user[0]->var_password))
                {
                    $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                    $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                echo "{\"status\" : \"200\",\"message\" : \"Login sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                }
                else 
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Password does not match\",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else 
            {
                echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
            }
        }
        /* Fetch user data all or single    */
        function userlist()
        {
            $email=$this->input->post('email');  // post id of which user data you will get
    
            if(!empty($email))
            { 
                $email=$this->input->post('email');
                $password=$this->input->post('password');
                $this->db->select('int_id,var_email,var_password');
                $this->db->from('tbl_user');
                $this->db->where('var_email', $email);
                $this->db->where('chr_status', 'A');
                $query = $this->db->get();
    
                $user = $query->result();
                if(!empty($user))
                {       
                    $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');  
                    $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                    $responce_json=json_encode($query->row_array());
                    echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
                }
                else
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else
            {
                $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                $query = $this->db->get('tbl_user');
                $responce_json=json_encode($query->result_array());
                echo "{\"status\" : \"200\",\"message\" : \"User data\",\"data\":".str_replace("<p>","",$responce_json). "}";
            }
        } 
    
        /*  Update user data   */
         function edit_user($data = array()) {
    
                $id = $this->input->post('id');
                $data['first_name'] = $this->input->post('first_name');
                /* $data['last_name'] = $this->input->post('last_name');
                $data['email'] = $this->input->post('email');
                $data['phone'] = $this->input->post('phone'); */
            if(!empty($data) && !empty($id)){
                if(!array_key_exists('modified', $data)){
                    $data['modified'] = date("Y-m-d H:i:s");
                }
    
                $update = $this->db->update('users', $data, array('id'=>$id));
                if($update){
                $message="User Update Sucessfully";
                $responce_json=json_encode($message); 
                echo "{\"status\" : \"200\",\"data\":".str_replace("<p>","",$responce_json). "}";
                }
    
            }
            else
            {
                return false;
            }
        } 
        /* change password  */
        function change_password()
        {
    
            $email=$this->input->post('email');
            $password=$this->input->post('password');
            $newpassword=$this->input->post('newpassword');
            //$conformnewpassword=$this->input->post('conformnewpassword');
            $this->db->select('int_id,var_email,var_password');
            $this->db->from('tbl_user');
            $this->db->where('var_email', $email);
            $this->db->where('chr_status', 'A');
            $query = $this->db->get();
    
            $user = $query->result();
            if(!empty($user))
            {
                if(verifyHashedPassword($password, $user[0]->var_password))
                {
                    //if($newpassword==$conformnewpassword)
                    //{
                        $data['var_password'] = getHashedPassword($newpassword);
                        $update = $this->db->update('tbl_user', $data, array('var_email'=>$email));
                        $this->db->select('var_email as email,var_fullname as fullname,dt_createddate as createdate');
                        $query = $this->db->get_where('tbl_user', array('var_email' => $email));
                        echo "{\"status\" : \"200\",\"message\" : \"Password change sucessfully\",\"data\":".str_replace("<p>","",json_encode($query->row_array())). "}";
                    /* }
                    else
                    {
                        echo "{\"status\" : \"404\",\"message\" : \"New pass and conform pass does not match \",\"data\":".str_replace("<p>","",'{}'). "}"; 
                    } */
                }
                else 
                {
                     echo "{\"status\" : \"404\",\"message\" : \"Invalid old password \",\"data\":".str_replace("<p>","",'{}'). "}";
                }
            }
            else 
            {
                echo "{\"status\" : \"404\",\"message\" : \"Invalid email \",\"data\":".str_replace("<p>","",'{}'). "}";
            }
        }
    
        /*
         * Delete user data
         */
        /* public function delete($id){
            $delete = $this->db->delete('users',array('id'=>$id));
            return $delete?true:false;
        } */
    
    }
    
     ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2017-07-30
      • 2018-06-16
      • 1970-01-01
      • 2011-09-15
      • 2018-02-05
      • 2015-02-11
      相关资源
      最近更新 更多