CheckSign.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace app\service\api;
  3. use app\service\ConfServiceFacade;
  4. use laytp\traits\Error;
  5. use think\facade\Config;
  6. use think\facade\Env;
  7. use think\facade\Request;
  8. /**
  9. * Api验证签名服务实现者
  10. * Class CheckSign
  11. * @package app\api\service
  12. */
  13. class CheckSign
  14. {
  15. use Error;
  16. protected $_noNeedCheckSign = [];//无需验证签名的方法名数组
  17. /**
  18. * 设置无需验证签名的方法名数组
  19. * @param array $noNeedCheckSign
  20. */
  21. public function setNoNeedCheckSign($noNeedCheckSign = [])
  22. {
  23. $this->_noNeedCheckSign = $noNeedCheckSign;
  24. }
  25. /**
  26. * 获取无需验证签名的方法名数组
  27. * @return array
  28. */
  29. public function getNoNeedCheckSign()
  30. {
  31. return $this->_noNeedCheckSign;
  32. }
  33. /**
  34. * 当前节点是否需要验证签名
  35. * @param bool $noNeedCheckSign
  36. * @return bool true:需要验证签名,false:不需要验证签名
  37. */
  38. public function needCheckSign($noNeedCheckSign = false)
  39. {
  40. $noNeedCheckSign === false && $noNeedCheckSign = $this->getNoNeedCheckSign();
  41. $noNeedCheckSign = is_array($noNeedCheckSign) ? $noNeedCheckSign : explode(',', $noNeedCheckSign);
  42. //为空表示所有方法都需要验证签名,返回true
  43. if (!$noNeedCheckSign) {
  44. return true;
  45. }
  46. $noNeedCheckSign = array_map('strtolower', $noNeedCheckSign);
  47. $request = Request::instance();
  48. //判断当前请求的操作名是否存在于不需要验证签名的方法名数组中,如果存在,表明不需要验证签名,返回false
  49. if (in_array(strtolower($request->action()), $noNeedCheckSign) || in_array('*', $noNeedCheckSign)) {
  50. return false;
  51. }
  52. //默认为需要验证签名
  53. return true;
  54. }
  55. /**
  56. * 验证签名
  57. */
  58. public function check()
  59. {
  60. $request = Request::instance();
  61. $requestTime = $request->header('request-time');
  62. $sign = $request->header('sign');
  63. $signKey = ConfServiceFacade::get('system.basic.signKey');
  64. $backendSign = strtoupper(md5(md5($requestTime).md5($signKey)));
  65. if($sign != $backendSign){
  66. $this->setError($backendSign);
  67. return false;
  68. }
  69. return true;
  70. }
  71. }