php实现接口http协议中的Authorization Basic认证、调用

1,062 阅读1分钟

我们应用API接口实现中通过Authorization Basic认证是比较常见的,下面谈谈使用php实现接口认证、调用的方法。

需求场景描述

应用系统API接口,需要通过Authorization Basic认证实现,接口方给客户端相应的密钥才能实现认证,并且客户端也通过Authorization Basic认证的调用来实现通信。

实现方法是,将http协议请求头中压入认证字符串,认证字符串可以以base64编码加密,格式如Authorization:Basic base64_encode("$name:$pwd")

接口实现Authorization Basic认证

php代码如下:


//一个验证用户的接口范例
public function validUser(){
      header("Content-Type: text/html; CharSet=UTF-8");
	  $requestHeaders = apache_request_headers();
 
	  if (array_key_exists('Authorization', $requestHeaders)) {
		list($username, $password) = explode(':', base64_decode(explode(' ', $requestHeaders['Authorization'])[1]));
//记录接口日志
		$log_content=date("Y-m-d H:i:s ", time())."Authorization username,password=".$username.';'.$password;
	    file_put_prepend ($log_content, $this->log_file); 
		//$auth_key=base64_decode(explode(' ', $requestHeaders['Authorization'])[1]);
		$pwd_en  = md5(md5($password));
		//$auth_key=$_POST['auth_key']; 
	    通过数据库或其他方式认证取得用户信息,$userInfo
			if (!empty($userInfo)) {
				$this->responCode(200);
				$this->uname=$username;
				//echo "登录成功";
			} else  {
				$this->responCode(403); exit;
			}
	  } else {
			$this->responCode(401); exit;
	  }
}
private function responCode($code){
		if (401 === $code) {
			header("401 Unauthorized");
			header("WWW-Authenticate: Basic");
		} elseif (403 === $code) {
			header("403 Forbidden");
		}
		else {
			header('200 OK');
		}
}

调用Authorization Basic认证API接口

public function callValidUser(){
     $url=$base_url.'/validuser';
	  $name='test';  $pwd='1234'; 
      $headers =array('Authorization:Basic '.base64_encode("$name:$pwd") );
  	  $ch = curl_init();
	  $postData=array('username'=>$_POST['username']);
	  curl_setopt($ch, CURLOPT_HEADER, 0);  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($ch, CURLOPT_POST, 1);  curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
      //curl_setopt($ch, CURLOPT_HTTPGET, true);	  curl_setopt($ch, CURLINFO_HEADER_OUT, true);	  
	  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);//跳过https验证
	  curl_setopt($ch, CURLOPT_URL, $url);
	  $response = curl_exec($ch);
	  // echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
	  curl_close($ch);
      echo $response;

}

原文链接:blog.csdn.net/yan_dk/arti…