php - 如何设置授权 header 以在android中调用rest api?

标签 php android json rest

我在我的 xampp 本地服务器中创建了一个测试 rest API。我执行了一些任务,如用户注册、登录用户等。 当用户注册时,它会为注册用户创建一个api_key。当用户尝试执行添加任务时,我使用了一个验证函数,该函数根据api_key<获取用户的唯一ID/strong>.

这是我在 php 中的身份验证函数:

function authenticate(\Slim\Route $route){
        //Getting request header
        $headers=apache_request_headers();
        $response=array();
        $app=\Slim\Slim::getInstance();


        //Verifying authorization Header

        if(isset($headers['Authorization'])){
            $db=new DbHandler();

            //Get api key
            $api_key=$headers['Authorization'];

            //validating api key

            if(!$db->isValidApiKey($api_key)){
                //Api key is not present in users table
                $response["error"]=TRUE;
                $response["message"]="Access_denied! Invalid api key";
                echoRespnse(401,$response);
                $app->stop();
            }
            else{
                global $student_id;

                //getUser primary key id

                $user=$db->getUserId($api_key);
                if($user!=NULL){
                    $student_id=$user['id'];
                }
            }
        }
        else{
            //api key is missing in header
            $response["error"]=TRUE;
            $response["message"]="Api key is missing";
            echoRespnse(400,$response);
            $api->stop();
        }
    }

这是我在 php 中的 IsValidApiKey() 函数。它检查 api_key 是否有效,我在请求本地服务器时在 header 中输入了它。

public function isValidApiKey($api_key) {
        $stmt = $this->conn->prepare("SELECT id from student WHERE api_key = ?");
        $stmt->bind_param("s", $api_key);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

这是将任务添加到我的数据库表中的任务:

$app->post('/tasks','authenticate',function() use ($app){
        //Check for required params
        verifyRequiredParams(array('task'));

        $response=array();
        $task=$app->request->post('task');
        global $user_id;
        $db=new DbHandler();

        //Creating new task

        $task_id=$db->createTask($user_id,$task);

        if($task_id!=NULL){
            $response["error"]=FALSE;
            $response["message"]="Task created successfully";
            $response["task_id"]=$task_id;
        }
        else{
            $response["error"]=TRUE;
            $response["message"]="Failed to create a task. please, try again!!";

        }
        echoRespnse(201,$response);

    });

在上面的任务中,我使用了我的身份验证功能。这意味着它会检查此 api_key 使用是否已经注册,如果是,则将任务添加到我的任务表中,否则,它会生成丢失的 api key 。

这是我的数据库表:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `password_hash` text NOT NULL,
  `api_key` varchar(32) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
);

当我使用 Advance API 客户端插件执行此操作时,它起作用了,因为我在它的 header 中传递了 api_key。

我想使用我的 android 应用程序添加任务,如何在 header 中添加 api_key 以便我可以使用 android 应用程序添加任务?

最佳答案

使用 HttpURlConnection 如下:

URL myURL = new URL("yoururl");
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");//  change as your requested method
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");

关于php - 如何设置授权 header 以在android中调用rest api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855266/

相关文章:

JavaScript - `document.head.appendChild` src 和 href 中缺少请求 cookie

php - 如果PHP Elastica中存在索引,如何获取现有的索引对象

使用 ProGuard 发布的应用程序中的 Android 错误

java - 在java中运行时更改json属性的值为1

php - 如何将 mysql_query 结果传递给查询字符串?

php - 即使代码工作正常,数据也不会保存到数据库中

json - 我如何使用 Go 漂亮地打印 JSON?

javascript - 如何从本地文件返回 React 中的 JSON 数组并使其映射到我的所有项目?

android - 如何在 viewModel 中使用双向绑定(bind)

java - Android studio 编译报错IllegalArgumentException