JWTAuth.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace oauth2\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\web\Controller;
  6. use yii\web\UnauthorizedHttpException;
  7. use yii\web\UnprocessableEntityHttpException;
  8. use yii\web\IdentityInterface;
  9. use oauth2\components\ServerRequest;
  10. use League\OAuth2\Server\CryptKey;
  11. use common\helpers\StringHelper;
  12. use oauth2\repository\AccessTokenRepository;
  13. /**
  14. * Class JWTAuth
  15. * @package oauth2\behaviors
  16. * @author jianyan74 <751393839@qq.com>
  17. */
  18. class JWTAuth extends Behavior
  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 UnauthorizedHttpException
  35. * @throws UnprocessableEntityHttpException
  36. */
  37. public function beforeAction($event)
  38. {
  39. if (in_array(Yii::$app->controller->action->id, $this->optional)) {
  40. return true;
  41. }
  42. $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
  43. $publicKeyPath = 'file://' . Yii::getAlias(Yii::$app->services->config->backendConfig('oauth2_rsa_public'));
  44. $server = new \League\OAuth2\Server\ResourceServer(
  45. $accessTokenRepository,
  46. new CryptKey($publicKeyPath, null, !StringHelper::isWindowsOS())
  47. );
  48. try {
  49. // 手动写入 header
  50. // Yii::$app->params['Authorization'] = 'Bearer ' . $token;
  51. $request = ServerRequest::fromGlobals();
  52. $server->validateAuthenticatedRequest($request);
  53. } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
  54. throw new UnauthorizedHttpException($exception->getMessage());
  55. } catch (\Exception $exception) {
  56. throw new UnprocessableEntityHttpException($exception->getMessage());
  57. }
  58. $user = $request->getAttributes();
  59. /** @var IdentityInterface $user */
  60. if ($user = Yii::$app->services->oauth2AccessToken->findByAccessToken($user['oauth_access_token_id'], $user['oauth_client_id'])) {
  61. Yii::$app->user->login($user);
  62. } else {
  63. throw new UnauthorizedHttpException('用户不存在');
  64. }
  65. return true;
  66. }
  67. }
粤ICP备19079148号