我使用codeIgniter为应用创建服务。 我创建了一个端点,其中用户id作为参数传入,然后输出该用户的json数据。 在用户登录时在应用程序上,我在服务器端创建一个JSON令牌。 我想在输出来自端点的json数据之前验证此令牌。我不确定我应该怎么做。我应该在我的codeIgniter控制器中加载视图之前检查令牌吗?
我有一个profiles_model,其中包含以下方法:
function get_profile($user_id){
//this function takes in a user_id as a parameter and gets that user's data from the profiles table in the database
$this->db->from('users');
$this->db->where('userID', $user_id);
$query = $this->db->get();
return $query->result(); //return the result
}
我有一个Profiles控制器类,它包含以下方法:
public function get_profile($user_id){
//this method gets the basic profile info of a user depending on what user id is passed in as a parameter.
//there are 6 profiles so user id should be between 1 to 6 to return any data
$this->load->model('Profiles_model'); //load our Profiles_model
//create an empty array to store the profile info
$data['profile'] = array();
foreach($this->Profiles_model->get_profile($user_id) as $key => $value){
array_push($data['profile'], array('user_id' => $value->userID,
'username' => $value->username,
'profile_image' => $value->profileImage,
'email_address' => $value->emailAddress));
}
//load our json_output.php view and pass in the $data array.
$this->load->view('json_output', $data);
}
json_output.php查看:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if(isset($profile)){
$output = $profile;
}
$this->output
->set_content_type('application/json', 'utf-8') //content type will be json
->set_output(json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
?>
使用JWT php类在应用程序上创建登录令牌。
$token = array();
$token['userID'] = $id;
$data['usertoken'] = JWT::encode($token, 'secret_server_key');
echo json_encode($data); //echo back to client side
对于应用程序上的后续http请求,我将令牌作为POST发送并在服务器端对其进行身份验证
if(isset($_POST["usertoken"])){
$token = JWT::decode($_POST['usertoken'], 'secret_server_key');
echo $token->userID; //this will be not available if the token has been tampered with
}
我想在我的终端中使用这段代码(我检查usertoken post变量),但我不确定在哪里放置它。我应该把它放在json_output.php视图中吗?谢谢
我在客户端的Javascript中的函数来检索Json。
function generateUserProfile(user_id){
var url = 'http://www.example.com/app_data/index.php/profiles/get_profile/' + user_id;
$.getJSON(url ,{format: "json"}).done(function(data){
var profile_image = "http://www.example.com/" + data[0].profile_image;
var profile_username = data[0].username + '<i class="fa fa-pencil edit"></i>';
var profile_email_address = data[0].email_address + '<i class="fa fa-pencil edit"></i>';
$("#profile_pic").attr('src', profile_image);
$("#profile_username").html(profile_username);
$("#profile_email_address").html(profile_email_address);
}); //end $.getJSON
}