AccessTokenRepository.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace oauth2\repository;
  3. use Yii;
  4. use yii\helpers\Json;
  5. use oauth2\entity\AccessTokenEntity;
  6. use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
  7. use League\OAuth2\Server\Entities\ClientEntityInterface;
  8. use League\OAuth2\Server\Entities\ScopeEntityInterface;
  9. use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
  10. /**
  11. * Class AccessTokenRepository
  12. * @package oauth2
  13. * @author jianyan74 <751393839@qq.com>
  14. */
  15. class AccessTokenRepository implements AccessTokenRepositoryInterface
  16. {
  17. /**
  18. * 创建新访问令牌时
  19. *
  20. * @param ClientEntityInterface $clientEntity
  21. * @param ScopeEntityInterface[] $scopes
  22. * @param mixed $userIdentifier
  23. *
  24. * @return AccessTokenEntityInterface
  25. */
  26. public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
  27. {
  28. // 需要返回 AccessTokenEntityInterface 对象
  29. // 需要在返回前,向 AccessTokenEntity 传入参数中对应属性
  30. $accessToken = new AccessTokenEntity();
  31. $accessToken->setClient($clientEntity);
  32. foreach ($scopes as $scope) {
  33. $accessToken->addScope($scope);
  34. }
  35. $accessToken->setUserIdentifier($userIdentifier);
  36. return $accessToken;
  37. }
  38. /**
  39. * 创建新令牌
  40. *
  41. * @param AccessTokenEntityInterface $accessTokenEntity
  42. */
  43. public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity)
  44. {
  45. // 创建新访问令牌时调用此方法
  46. // 可以用于持久化存储访问令牌,持久化数据库自行选择
  47. // 可以使用参数中的 AccessTokenEntityInterface 对象,获得有价值的信息:
  48. $date = $accessTokenEntity->getExpiryDateTime(); // 获得令牌过期时间
  49. $date = Json::decode(Json::encode($date));
  50. // 创建token
  51. Yii::$app->services->oauth2AccessToken->create(
  52. $accessTokenEntity->getClient()->getIdentifier(), // 获得客户端标识符
  53. $accessTokenEntity->getClient()->getGrantType(),
  54. $accessTokenEntity->getIdentifier(),
  55. $date['date'],
  56. $accessTokenEntity->getUserIdentifier(), // 获得用户标识符
  57. $accessTokenEntity->getScopes()// 获得权限范围
  58. );
  59. }
  60. /**
  61. * 当使用刷新令牌获取访问令牌时调用此方法
  62. * 原刷新令牌将删除,创建新的刷新令牌
  63. *
  64. * @param string $tokenId
  65. */
  66. public function revokeAccessToken($tokenId)
  67. {
  68. // 可将其在持久化存储中过期
  69. Yii::$app->services->oauth2AccessToken->deleteByAccessToken($tokenId);
  70. }
  71. /**
  72. * 资源服务器验证访问令牌时将调用此方法
  73. * 用于验证访问令牌是否已被删除
  74. *
  75. * @param string $tokenId
  76. * @return bool
  77. */
  78. public function isAccessTokenRevoked($tokenId)
  79. {
  80. // return true 已删除,false 未删除
  81. return empty(Yii::$app->services->oauth2AccessToken->findByAccessToken($tokenId));
  82. }
  83. }
粤ICP备19079148号