ServerService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace services\oauth2;
  3. use Yii;
  4. use common\components\Service;
  5. use common\helpers\StringHelper;
  6. use oauth2\repository\ClientRepository;
  7. use oauth2\repository\ScopeRepository;
  8. use oauth2\repository\AccessTokenRepository;
  9. use League\OAuth2\Server\AuthorizationServer;
  10. use League\OAuth2\Server\CryptKey;
  11. /**
  12. * Class ServerService
  13. * @package services\oauth2
  14. * @author jianyan74 <751393839@qq.com>
  15. */
  16. class ServerService extends Service
  17. {
  18. /**
  19. * @var AuthorizationServer
  20. */
  21. private $_server;
  22. /**
  23. * @return AuthorizationServer
  24. */
  25. public function get(): AuthorizationServer
  26. {
  27. return $this->_server;
  28. }
  29. /**
  30. * @param $grant
  31. * @throws \Exception
  32. */
  33. public function set($grant)
  34. {
  35. $clientRepository = new ClientRepository(); // Interface: ClientRepositoryInterface
  36. $scopeRepository = new ScopeRepository(); // Interface: ScopeRepositoryInterface
  37. $accessTokenRepository = new AccessTokenRepository(); // Interface: AccessTokenRepositoryInterface
  38. // 初始化 server
  39. $this->_server = new AuthorizationServer(
  40. $clientRepository,
  41. $accessTokenRepository,
  42. $scopeRepository,
  43. $this->getPrivateKey(),
  44. $this->getEncryptionKey()
  45. );
  46. // 将授权码授权类型添加进 server
  47. $this->_server->enableGrantType(
  48. $grant,
  49. new \DateInterval(Yii::$app->params['user.accessTokenExpire'] ?? 'PT1H') // 设置访问令牌过期时间1小时
  50. );
  51. }
  52. /**
  53. * 私钥文件
  54. *
  55. * @return CryptKey|string
  56. */
  57. public function getPrivateKey()
  58. {
  59. $privateKey = 'file://' . Yii::getAlias(Yii::$app->services->config->backendConfig('oauth2_rsa_private'));
  60. // 如果私钥文件有密码
  61. if (!empty(Yii::$app->services->config->backendConfig('oauth2_rsa_private_encryption'))) {
  62. $privateKey = new CryptKey(
  63. $privateKey,
  64. Yii::$app->services->config->backendConfig('oauth2_rsa_private_password'),
  65. !StringHelper::isWindowsOS()
  66. );
  67. } else {
  68. $privateKey = new CryptKey($privateKey, null, !StringHelper::isWindowsOS());
  69. }
  70. return $privateKey;
  71. }
  72. /**
  73. * 加密密钥字符串
  74. *
  75. * @return string
  76. */
  77. public function getEncryptionKey(): string
  78. {
  79. $encryptionKey = Yii::$app->services->config->backendConfig('oauth2_encryption_key'); // 加密密钥字符串
  80. // generate using base64_encode(random_bytes(32))
  81. // $encryptionKey = Key::loadFromAsciiSafeString($encryptionKey); //如果通过 generate-defuse-key 脚本生成的字符串,可使用此方法传入
  82. return $encryptionKey;
  83. }
  84. }
粤ICP备19079148号