HttpSignAuth.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace common\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\web\Controller;
  6. use yii\web\UnprocessableEntityHttpException;
  7. use common\helpers\EncryptionHelper;
  8. use common\models\forms\SignAuthForm;
  9. /**
  10. * http 签名验证
  11. *
  12. * Class HttpSignAuth
  13. * @package api\behaviors
  14. * @author qimall
  15. */
  16. class HttpSignAuth extends Behavior
  17. {
  18. /**
  19. * 方法白名单
  20. *
  21. * @var array
  22. */
  23. public $optional = [];
  24. /**
  25. * @return array
  26. */
  27. public function events()
  28. {
  29. return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
  30. }
  31. /**
  32. * @param $event
  33. * @return bool
  34. * @throws UnprocessableEntityHttpException
  35. */
  36. public function beforeAction($event)
  37. {
  38. if (in_array(Yii::$app->controller->action->id, $this->optional)) {
  39. return true;
  40. }
  41. $data = Yii::$app->request->get();
  42. $model = new SignAuthForm();
  43. $model->attributes = $data;
  44. if (!$model->validate()) {
  45. throw new UnprocessableEntityHttpException(Yii::$app->debris->analyErr($model->getFirstErrors()));
  46. }
  47. return EncryptionHelper::decodeUrlParam($data, $model->appSecret);
  48. }
  49. }