ClientCredentialsController.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace oauth2\controllers;
  3. use Yii;
  4. use GuzzleHttp\Psr7\ServerRequest;
  5. use oauth2\components\Response;
  6. use common\helpers\ResultHelper;
  7. /**
  8. * 客户端模式(无用户,用户向客户端注册,然后客户端以自己的名义向’服务端’获取资源)
  9. *
  10. * Class ClientCredentialsController
  11. * @package oauth2\controllers
  12. * @author jianyan74 <751393839@qq.com>
  13. */
  14. class ClientCredentialsController extends OnAuthController
  15. {
  16. public $modelClass = '';
  17. /**
  18. * 不用进行登录验证的方法
  19. * 例如: ['index', 'update', 'create', 'view', 'delete']
  20. * 默认全部需要验证
  21. *
  22. * @var array
  23. */
  24. protected $authOptional = ['create'];
  25. /**
  26. * @throws \Exception
  27. */
  28. public function init()
  29. {
  30. parent::init();
  31. $grant = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
  32. // 写入服务
  33. Yii::$app->services->oauth2Server->set($grant);
  34. }
  35. /**
  36. * @return mixed
  37. */
  38. public function actionCreate()
  39. {
  40. /* @var \League\OAuth2\Server\AuthorizationServer $server */
  41. $server = Yii::$app->services->oauth2Server->get();
  42. $response = new Response();
  43. $request = ServerRequest::fromGlobals();
  44. // Try to respond to the request
  45. try {
  46. $server->respondToAccessTokenRequest($request, $response);
  47. } catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
  48. return ResultHelper::json(422, $exception->getMessage());
  49. } catch (\Exception $exception) {
  50. return ResultHelper::json(422, $exception->getMessage());
  51. }
  52. }
  53. /**
  54. * 权限验证
  55. *
  56. * @param string $action 当前的方法
  57. * @param null $model 当前的模型类
  58. * @param array $params $_GET变量
  59. * @throws \yii\web\BadRequestHttpException
  60. */
  61. public function checkAccess($action, $model = null, $params = [])
  62. {
  63. // 方法名称
  64. if (in_array($action, ['index', 'view', 'update', 'delete'])) {
  65. throw new \yii\web\BadRequestHttpException('您的权限不足,如需要请联系管理员');
  66. }
  67. }
  68. }
粤ICP备19079148号