AuthorizeController.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. <?php
  2. namespace frontend\modules\open\controllers;
  3. use Yii;
  4. use yii\web\Controller;
  5. use yii\web\NotFoundHttpException;
  6. use oauth2\components\Response;
  7. use oauth2\entity\UserEntity;
  8. use oauth2\repository\AuthCodeRepository;
  9. use oauth2\repository\RefreshTokenRepository;
  10. use oauth2\entity\ScopeEntity;
  11. use League\OAuth2\Server\Exception\OAuthServerException;
  12. use League\OAuth2\Server\Grant\AuthCodeGrant;
  13. use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
  14. use GuzzleHttp\Psr7\ServerRequest;
  15. use frontend\forms\LoginForm;
  16. /**
  17. * 授权码模式(即先登录获取code,再获取token)
  18. *
  19. * Class AuthorizeController
  20. * @package frontend\modules\open\controllers
  21. * @author jianyan74 <751393839@qq.com>
  22. */
  23. class AuthorizeController extends Controller
  24. {
  25. /**
  26. * @var bool
  27. */
  28. public $enableCsrfValidation = false;
  29. /**
  30. * @throws \Exception
  31. */
  32. public function init()
  33. {
  34. parent::init();
  35. // 初始化存储库
  36. $authCodeRepository = new AuthCodeRepository(); // Interface: AuthCodeRepositoryInterface
  37. $refreshTokenRepository = new RefreshTokenRepository(); // Interface: RefreshTokenRepositoryInterface
  38. // 授权码授权类型初始化
  39. $grant = new AuthCodeGrant(
  40. $authCodeRepository,
  41. $refreshTokenRepository,
  42. new \DateInterval(Yii::$app->params['user.codeExpire']) // 设置授权码过期时间为10分钟
  43. );
  44. $grant->setRefreshTokenTTL(new \DateInterval(Yii::$app->params['user.refreshTokenExpire'])); // 设置刷新令牌过期时间1个月
  45. Yii::$app->services->oauth2Server->set($grant); // 写入服务
  46. }
  47. /**
  48. * @return string|void
  49. * @throws NotFoundHttpException
  50. */
  51. public function actionIndex()
  52. {
  53. $server = Yii::$app->services->oauth2Server->get();
  54. $request = ServerRequest::fromGlobals();
  55. try {
  56. // 验证 HTTP 请求,并返回 authRequest 对象
  57. $authRequest = $server->validateAuthorizationRequest($request);
  58. // 此时应将 authRequest 对象序列化后存在当前会话(session)中
  59. Yii::$app->session->set('authRequest', serialize($authRequest));
  60. } catch (OAuthServerException $exception) {
  61. throw new NotFoundHttpException($exception->getMessage());
  62. } catch (\Exception $exception) {
  63. throw new NotFoundHttpException($exception->getMessage());
  64. }
  65. // 判断是否已登录
  66. if (!Yii::$app->user->isGuest) {
  67. return $this->render('remind', []);
  68. }
  69. $model = new LoginForm();
  70. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  71. return $this->callback();
  72. }
  73. $model->password = '';
  74. return $this->render('login', [
  75. 'model' => $model,
  76. ]);
  77. }
  78. /**
  79. * Logs out the current user.
  80. *
  81. * @return mixed
  82. */
  83. public function actionLogout()
  84. {
  85. Yii::$app->user->logout();
  86. return $this->redirect([
  87. 'index',
  88. 'response_type' => Yii::$app->request->get('response_type'),
  89. 'client_id' => Yii::$app->request->get('client_id'),
  90. 'redirect_uri' => Yii::$app->request->get('redirect_uri'),
  91. 'state' => Yii::$app->request->get('state'),
  92. 'scope' => Yii::$app->request->get('scope'),
  93. ]);
  94. }
  95. /**
  96. * 授权登录
  97. *
  98. * @return void|\yii\web\Response
  99. * @throws NotFoundHttpException
  100. */
  101. public function actionAuthorization()
  102. {
  103. // 判断是否已登录
  104. if (!Yii::$app->user->isGuest) {
  105. return $this->callback();
  106. }
  107. return $this->redirect(['index']);
  108. }
  109. /**
  110. * @throws NotFoundHttpException
  111. *
  112. * return mix
  113. */
  114. protected function callback()
  115. {
  116. $server = Yii::$app->services->oauth2Server->get();
  117. $response = new Response();
  118. try {
  119. /** @var AuthorizationRequest $authRequest 在会话(session)中取出 authRequest 对象 */
  120. $authRequest = unserialize(Yii::$app->session->get('authRequest'));
  121. // 设置用户实体(userEntity)
  122. $user = new UserEntity();
  123. $user->setIdentifier(Yii::$app->user->id);
  124. $authRequest->setUser($user);
  125. // 设置权限范围
  126. $scopeEntity = new ScopeEntity();
  127. $scopeEntity->setIdentifier('basic_info');
  128. $authRequest->setScopes([$scopeEntity]);
  129. // true = 批准,false = 拒绝
  130. $authRequest->setAuthorizationApproved(true);
  131. // 完成后重定向至客户端请求重定向地址
  132. $server->completeAuthorizationRequest($authRequest, $response);
  133. } catch (OAuthServerException $exception) {
  134. throw new NotFoundHttpException($exception->getMessage());
  135. } catch (\Exception $exception) {
  136. throw new NotFoundHttpException($exception->getMessage());
  137. }
  138. }
  139. }
粤ICP备19079148号