簡體   English   中英

如何在 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 控制器內對控制器進行臟實例化。

添加類application\\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);
}

閱讀有關CodeIgniter 中的庫的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM