ImplicitController.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 GuzzleHttp\Psr7\ServerRequest;
  9. use League\OAuth2\Server\Grant\ImplicitGrant;
  10. /**
  11. * 简化模式(在redirect_uri 的Hash传递token; Auth客户端运行在浏览器中,如JS,Flash)
  12. *
  13. * Class ImplicitController
  14. * @package frontend\modules\open\controllers
  15. * @author jianyan74 <751393839@qq.com>
  16. */
  17. class ImplicitController extends Controller
  18. {
  19. /**
  20. * @throws \Exception
  21. */
  22. public function init()
  23. {
  24. parent::init();
  25. $grant = new ImplicitGrant(new \DateInterval(Yii::$app->params['user.accessTokenExpire']));
  26. Yii::$app->services->oauth2Server->set($grant); // 写入服务
  27. }
  28. /**
  29. * @throws NotFoundHttpException
  30. */
  31. public function actionIndex()
  32. {
  33. /* @var \League\OAuth2\Server\AuthorizationServer $server */
  34. $server = Yii::$app->services->oauth2Server->get();
  35. $response = new Response();
  36. $request = ServerRequest::fromGlobals();
  37. // Try to respond to the request
  38. try {
  39. // 验证HTTP请求并返回
  40. $authRequest = $server->validateAuthorizationRequest($request);
  41. // 是否授权成功
  42. $authRequest->setAuthorizationApproved(true);
  43. $authRequest->setUser(new UserEntity());
  44. $server->completeAuthorizationRequest($authRequest, $response);
  45. } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
  46. throw new NotFoundHttpException($exception->getMessage());
  47. } catch (\Exception $exception) {
  48. throw new NotFoundHttpException($exception->getMessage());
  49. }
  50. }
  51. }
粤ICP备19079148号