BearerAuth.php 949 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace common\filters\auth;
  3. use yii\filters\auth\AuthMethod;
  4. /**
  5. * Class BearerAuth
  6. * @package common\filters\auth
  7. */
  8. class BearerAuth extends AuthMethod
  9. {
  10. public $header = 'FzmMQ';
  11. /**
  12. * @var string the HTTP authentication realm
  13. */
  14. public $realm = 'api';
  15. /**
  16. * @inheritdoc
  17. */
  18. public function authenticate($user, $request, $response)
  19. {
  20. $authHeader = $request->getHeaders()->get('Authorization');
  21. if ($authHeader !== null && preg_match('/^' . $this->header . '\s+(.*?):(.*?)$/', $authHeader, $matches)) {
  22. $identity = $user->loginByAccessToken($matches[1].':'.$matches[2], get_class($this));
  23. if ($identity === null) {
  24. $this->handleFailure($response);
  25. }
  26. return $identity;
  27. }
  28. return null;
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. public function challenge($response)
  34. {
  35. $response->getHeaders()->set('WWW-Authenticate', "Bearer realm=\"{$this->realm}\"");
  36. }
  37. }