Home Backend Development PHP Tutorial Implementation of API interface security verification function

Implementation of API interface security verification function

Mar 24, 2018 pm 01:36 PM
api Function accomplish

This time I will bring you the implementation of the api interface security verification function. What are the precautions for implementing the api interface security verification function. The following is a practical case, let’s take a look.

php api interface

In actual work, it is common to use PHP to write api interfaces. After writing the interface in PHP, the front desk You can obtain the data provided by the interface through the link, and the returned data is generally divided into two situations, xml and json. In this process, the server does not know the source of the request. It may be that someone else illegally calls our interface. , to obtain data, therefore security verification must be used.

Verification principle

Schematic diagram

Principle

It can be clearly seen from the picture that if the front desk wants to call the interface, it needs to use several parameters to generate a signature.

Time stamp: Current time

Random number: Randomly generated random number

Password: During front-end and back-end development, an identifier known to both parties , which is equivalent to the secret code

Algorithm rules: The agreed operation rules, the above three parameters can use the algorithm rules to generate a signature.

The frontend generates a signature. When accessing the interface is required, the timestamp, random number, and signature are passed to the backend through the URL. After getting the timestamp and random number in the background, it calculates the signature through the same algorithm rules, and then compares it with the passed signature. If it is the same, the data is returned.

Algorithm Rules

In front-end and back-end interactions, algorithm rules are very important. Both front-end and back-end must calculate signatures through algorithm rules. As for how to set the rules, it depends on how you like it.

My algorithm rules are

1 The timestamp, random number, and password are sorted in case order of the first letter

2 and then spliced ​​into a string

3 Perform sha1 encryption

4 Then perform MD5 encryption

5 Convert to uppercase.

Front desk

I don’t have an actual front desk here. I directly use a PHP file instead of the front desk, and then simulate a GET request through CURL. I am using the TP framework and the URL format is pathinfo format.

Source code

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/16 0016
 * Time: 15:56
 */
namespace Client\Controller;
use Think\Controller;
class ClientController extends Controller{
 const TOKEN = &#39;API&#39;;
 //模拟前台请求服务器api接口
 public function getDataFromServer(){
  //时间戳
  $timeStamp = time();
  //随机数
  $randomStr = $this -> createNonceStr();
  //生成签名
  $signature = $this -> arithmetic($timeStamp,$randomStr);
  //url地址
  $url = "http://www.apitest.com/Server/Server/respond/t/{$timeStamp}/r/{$randomStr}/s/{$signature}";
  $result = $this -> httpGet($url);
  dump($result);
 }
 //curl模拟get请求。
 private function httpGet($url){
  $curl = curl_init();
  //需要请求的是哪个地址
  curl_setopt($curl,CURLOPT_URL,$url);
  //表示把请求的数据已文件流的方式输出到变量中
  curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
  $result = curl_exec($curl);
  curl_close($curl);
  return $result;
 }
 //随机生成字符串
 private function createNonceStr($length = 8) {
  $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  $str = "";
  for ($i = 0; $i < $length; $i++) {
   $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  }
  return "z".$str;
 }
 /**
  * @param $timeStamp 时间戳
  * @param $randomStr 随机字符串
  * @return string 返回签名
  */
 private function arithmetic($timeStamp,$randomStr){
  $arr[&#39;timeStamp&#39;] = $timeStamp;
  $arr[&#39;randomStr&#39;] = $randomStr;
  $arr[&#39;token&#39;] = self::TOKEN;
  //按照首字母大小写顺序排序
  sort($arr,SORT_STRING);
  //拼接成字符串
  $str = implode($arr);
  //进行加密
  $signature = sha1($str);
  $signature = md5($signature);
  //转换成大写
  $signature = strtoupper($signature);
  return $signature;
 }
}
Copy after login

Server side

Accept foreground data for verification

Source code

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/16 0016
 * Time: 16:01
 */
namespace Server\Controller;
use Think\Controller;
class ServerController extends Controller{
 const TOKEN = &#39;API&#39;;
 //响应前台的请求
 public function respond(){
  //验证身份
  $timeStamp = $_GET[&#39;t&#39;];
  $randomStr = $_GET[&#39;r&#39;];
  $signature = $_GET[&#39;s&#39;];
  $str = $this -> arithmetic($timeStamp,$randomStr);
  if($str != $signature){
   echo "-1";
   exit;
  }
  //模拟数据
  $arr['name'] = 'api';
  $arr['age'] = 15;
  $arr['address'] = 'zz';
  $arr['ip'] = "192.168.0.1";
  echo json_encode($arr);
 }
 /**
  * @param $timeStamp 时间戳
  * @param $randomStr 随机字符串
  * @return string 返回签名
  */
 public function arithmetic($timeStamp,$randomStr){
  $arr['timeStamp'] = $timeStamp;
  $arr['randomStr'] = $randomStr;
  $arr['token'] = self::TOKEN;
  //按照首字母大小写顺序排序
  sort($arr,SORT_STRING);
  //拼接成字符串
  $str = implode($arr);
  //进行加密
  $signature = sha1($str);
  $signature = md5($signature);
  //转换成大写
  $signature = strtoupper($signature);
  return $signature;
 }
}
Copy after login

Result

string(57) "{"name":"api","age":15,"address":"zz","ip":"192.168.0.1"}"
Copy after login

Summary

This method is just one of them. In fact, there are many methods that can be used for security verification.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of PHP callback functions and anonymous functions

Access directory service permissions of phpstudy2018

The above is the detailed content of Implementation of API interface security verification function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

See all articles