QueryParamAuth.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: nodelog
  5. * Date: 2020/6/20
  6. * Time: 16:38
  7. */
  8. namespace api\common\behaviors;
  9. use Yii;
  10. use yii\filters\auth\AuthMethod;
  11. use yii\web\UnauthorizedHttpException;
  12. class QueryParamAuth extends AuthMethod
  13. {
  14. public $forceAuth = true;//是否强制验证,false则只登录,不关心是否成功
  15. public $tokenParam = 'token';
  16. /**
  17. * @inheritdoc
  18. */
  19. public function authenticate($user, $request, $response)
  20. {
  21. $accessToken = $request->headers->get($this->tokenParam);
  22. if (is_string($accessToken)) {
  23. $identity = $user->loginByAccessToken($accessToken, get_class($this));
  24. if ($identity !== null) {
  25. return $identity;
  26. }
  27. }
  28. if ($accessToken !== null && $this->forceAuth) {
  29. $this->handleFailure($response);
  30. }
  31. return null;
  32. }
  33. /**
  34. * @param $action
  35. * @return bool
  36. * @throws UnauthorizedHttpException
  37. * @author nodelog
  38. */
  39. public function beforeAction($action)
  40. {
  41. $response = $this->response ? : Yii::$app->getResponse();
  42. try {
  43. $identity = $this->authenticate(
  44. $this->user ? : Yii::$app->getUser(),
  45. $this->request ? : Yii::$app->getRequest(),
  46. $response
  47. );
  48. } catch (UnauthorizedHttpException $e) {
  49. if ($this->isOptional($action) || !$this->forceAuth) {
  50. return true;
  51. }
  52. throw $e;
  53. }
  54. if ($identity !== null || $this->isOptional($action) || !$this->forceAuth) {
  55. return true;
  56. } else {
  57. $this->challenge($response);
  58. $this->handleFailure($response);
  59. return false;
  60. }
  61. }
  62. }