Server.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. <?php
  2. namespace OAuth2;
  3. use OAuth2\Controller\ResourceControllerInterface;
  4. use OAuth2\Controller\ResourceController;
  5. use OAuth2\OpenID\Controller\UserInfoControllerInterface;
  6. use OAuth2\OpenID\Controller\UserInfoController;
  7. use OAuth2\OpenID\Controller\AuthorizeController as OpenIDAuthorizeController;
  8. use OAuth2\OpenID\ResponseType\AuthorizationCode as OpenIDAuthorizationCodeResponseType;
  9. use OAuth2\OpenID\Storage\AuthorizationCodeInterface as OpenIDAuthorizationCodeInterface;
  10. use OAuth2\OpenID\GrantType\AuthorizationCode as OpenIDAuthorizationCodeGrantType;
  11. use OAuth2\Controller\AuthorizeControllerInterface;
  12. use OAuth2\Controller\AuthorizeController;
  13. use OAuth2\Controller\TokenControllerInterface;
  14. use OAuth2\Controller\TokenController;
  15. use OAuth2\ClientAssertionType\ClientAssertionTypeInterface;
  16. use OAuth2\ClientAssertionType\HttpBasic;
  17. use OAuth2\ResponseType\ResponseTypeInterface;
  18. use OAuth2\ResponseType\AuthorizationCode as AuthorizationCodeResponseType;
  19. use OAuth2\ResponseType\AccessToken;
  20. use OAuth2\ResponseType\JwtAccessToken;
  21. use OAuth2\OpenID\ResponseType\CodeIdToken;
  22. use OAuth2\OpenID\ResponseType\IdToken;
  23. use OAuth2\OpenID\ResponseType\IdTokenToken;
  24. use OAuth2\TokenType\TokenTypeInterface;
  25. use OAuth2\TokenType\Bearer;
  26. use OAuth2\GrantType\GrantTypeInterface;
  27. use OAuth2\GrantType\UserCredentials;
  28. use OAuth2\GrantType\ClientCredentials;
  29. use OAuth2\GrantType\RefreshToken;
  30. use OAuth2\GrantType\AuthorizationCode;
  31. use OAuth2\Storage\JwtAccessToken as JwtAccessTokenStorage;
  32. use OAuth2\Storage\JwtAccessTokenInterface;
  33. /**
  34. * Server class for OAuth2
  35. * This class serves as a convience class which wraps the other Controller classes
  36. *
  37. * @see OAuth2\Controller\ResourceController
  38. * @see OAuth2\Controller\AuthorizeController
  39. * @see OAuth2\Controller\TokenController
  40. */
  41. class Server implements ResourceControllerInterface,
  42. AuthorizeControllerInterface,
  43. TokenControllerInterface,
  44. UserInfoControllerInterface
  45. {
  46. // misc properties
  47. /**
  48. * @var Response
  49. */
  50. protected $response;
  51. /**
  52. * @var array
  53. */
  54. protected $config;
  55. /**
  56. * @var array
  57. */
  58. protected $storages;
  59. // servers
  60. /**
  61. * @var AuthorizeControllerInterface
  62. */
  63. protected $authorizeController;
  64. /**
  65. * @var TokenControllerInterface
  66. */
  67. protected $tokenController;
  68. /**
  69. * @var ResourceControllerInterface
  70. */
  71. protected $resourceController;
  72. /**
  73. * @var UserInfoControllerInterface
  74. */
  75. protected $userInfoController;
  76. // config classes
  77. protected $grantTypes;
  78. protected $responseTypes;
  79. protected $tokenType;
  80. /**
  81. * @var ScopeInterface
  82. */
  83. protected $scopeUtil;
  84. protected $clientAssertionType;
  85. protected $storageMap = array(
  86. 'access_token' => 'OAuth2\Storage\AccessTokenInterface',
  87. 'authorization_code' => 'OAuth2\Storage\AuthorizationCodeInterface',
  88. 'client_credentials' => 'OAuth2\Storage\ClientCredentialsInterface',
  89. 'client' => 'OAuth2\Storage\ClientInterface',
  90. 'refresh_token' => 'OAuth2\Storage\RefreshTokenInterface',
  91. 'user_credentials' => 'OAuth2\Storage\UserCredentialsInterface',
  92. 'user_claims' => 'OAuth2\OpenID\Storage\UserClaimsInterface',
  93. 'public_key' => 'OAuth2\Storage\PublicKeyInterface',
  94. 'jwt_bearer' => 'OAuth2\Storage\JWTBearerInterface',
  95. 'scope' => 'OAuth2\Storage\ScopeInterface',
  96. );
  97. protected $responseTypeMap = array(
  98. 'token' => 'OAuth2\ResponseType\AccessTokenInterface',
  99. 'code' => 'OAuth2\ResponseType\AuthorizationCodeInterface',
  100. 'id_token' => 'OAuth2\OpenID\ResponseType\IdTokenInterface',
  101. 'id_token token' => 'OAuth2\OpenID\ResponseType\IdTokenTokenInterface',
  102. 'code id_token' => 'OAuth2\OpenID\ResponseType\CodeIdTokenInterface',
  103. );
  104. /**
  105. * @param mixed $storage (array or OAuth2\Storage) - single object or array of objects implementing the
  106. * required storage types (ClientCredentialsInterface and AccessTokenInterface as a minimum)
  107. * @param array $config specify a different token lifetime, token header name, etc
  108. * @param array $grantTypes An array of OAuth2\GrantType\GrantTypeInterface to use for granting access tokens
  109. * @param array $responseTypes Response types to use. array keys should be "code" and and "token" for
  110. * Access Token and Authorization Code response types
  111. * @param \OAuth2\TokenType\TokenTypeInterface $tokenType The token type object to use. Valid token types are "bearer" and "mac"
  112. * @param \OAuth2\ScopeInterface $scopeUtil The scope utility class to use to validate scope
  113. * @param \OAuth2\ClientAssertionType\ClientAssertionTypeInterface $clientAssertionType The method in which to verify the client identity. Default is HttpBasic
  114. *
  115. * @ingroup oauth2_section_7
  116. */
  117. public function __construct($storage = array(), array $config = array(), array $grantTypes = array(), array $responseTypes = array(), TokenTypeInterface $tokenType = null, ScopeInterface $scopeUtil = null, ClientAssertionTypeInterface $clientAssertionType = null)
  118. {
  119. $storage = is_array($storage) ? $storage : array($storage);
  120. $this->storages = array();
  121. foreach ($storage as $key => $service) {
  122. $this->addStorage($service, $key);
  123. }
  124. // merge all config values. These get passed to our controller objects
  125. $this->config = array_merge(array(
  126. 'use_jwt_access_tokens' => false,
  127. 'store_encrypted_token_string' => true,
  128. 'use_openid_connect' => false,
  129. 'id_lifetime' => 3600,
  130. 'access_lifetime' => 3600,
  131. 'www_realm' => 'Service',
  132. 'token_param_name' => 'access_token',
  133. 'token_bearer_header_name' => 'Bearer',
  134. 'enforce_state' => true,
  135. 'require_exact_redirect_uri' => true,
  136. 'allow_implicit' => false,
  137. 'allow_credentials_in_request_body' => true,
  138. 'allow_public_clients' => true,
  139. 'always_issue_new_refresh_token' => false,
  140. 'unset_refresh_token_after_use' => true,
  141. ), $config);
  142. foreach ($grantTypes as $key => $grantType) {
  143. $this->addGrantType($grantType, $key);
  144. }
  145. foreach ($responseTypes as $key => $responseType) {
  146. $this->addResponseType($responseType, $key);
  147. }
  148. $this->tokenType = $tokenType;
  149. $this->scopeUtil = $scopeUtil;
  150. $this->clientAssertionType = $clientAssertionType;
  151. if ($this->config['use_openid_connect']) {
  152. $this->validateOpenIdConnect();
  153. }
  154. }
  155. public function getAuthorizeController()
  156. {
  157. if (is_null($this->authorizeController)) {
  158. $this->authorizeController = $this->createDefaultAuthorizeController();
  159. }
  160. return $this->authorizeController;
  161. }
  162. public function getTokenController()
  163. {
  164. if (is_null($this->tokenController)) {
  165. $this->tokenController = $this->createDefaultTokenController();
  166. }
  167. return $this->tokenController;
  168. }
  169. public function getResourceController()
  170. {
  171. if (is_null($this->resourceController)) {
  172. $this->resourceController = $this->createDefaultResourceController();
  173. }
  174. return $this->resourceController;
  175. }
  176. public function getUserInfoController()
  177. {
  178. if (is_null($this->userInfoController)) {
  179. $this->userInfoController = $this->createDefaultUserInfoController();
  180. }
  181. return $this->userInfoController;
  182. }
  183. /**
  184. * every getter deserves a setter
  185. *
  186. * @param AuthorizeControllerInterface $authorizeController
  187. */
  188. public function setAuthorizeController(AuthorizeControllerInterface $authorizeController)
  189. {
  190. $this->authorizeController = $authorizeController;
  191. }
  192. /**
  193. * every getter deserves a setter
  194. *
  195. * @param TokenControllerInterface $tokenController
  196. */
  197. public function setTokenController(TokenControllerInterface $tokenController)
  198. {
  199. $this->tokenController = $tokenController;
  200. }
  201. /**
  202. * every getter deserves a setter
  203. *
  204. * @param ResourceControllerInterface $resourceController
  205. */
  206. public function setResourceController(ResourceControllerInterface $resourceController)
  207. {
  208. $this->resourceController = $resourceController;
  209. }
  210. /**
  211. * every getter deserves a setter
  212. *
  213. * @param UserInfoControllerInterface $userInfoController
  214. */
  215. public function setUserInfoController(UserInfoControllerInterface $userInfoController)
  216. {
  217. $this->userInfoController = $userInfoController;
  218. }
  219. /**
  220. * Return claims about the authenticated end-user.
  221. * This would be called from the "/UserInfo" endpoint as defined in the spec.
  222. *
  223. * @param $request - \OAuth2\RequestInterface
  224. * Request object to grant access token
  225. *
  226. * @param $response - \OAuth2\ResponseInterface
  227. * Response object containing error messages (failure) or user claims (success)
  228. *
  229. * @return ResponseInterface
  230. *
  231. * @throws \InvalidArgumentException
  232. * @throws \LogicException
  233. *
  234. * @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  235. */
  236. public function handleUserInfoRequest(RequestInterface $request, ResponseInterface $response = null)
  237. {
  238. $this->response = is_null($response) ? new Response() : $response;
  239. $this->getUserInfoController()->handleUserInfoRequest($request, $this->response);
  240. return $this->response;
  241. }
  242. /**
  243. * Grant or deny a requested access token.
  244. * This would be called from the "/token" endpoint as defined in the spec.
  245. * Obviously, you can call your endpoint whatever you want.
  246. *
  247. * @param $request - \OAuth2\RequestInterface
  248. * Request object to grant access token
  249. *
  250. * @param $response - \OAuth2\ResponseInterface
  251. * Response object containing error messages (failure) or access token (success)
  252. *
  253. * @return ResponseInterface
  254. *
  255. * @throws \InvalidArgumentException
  256. * @throws \LogicException
  257. *
  258. * @see http://tools.ietf.org/html/rfc6749#section-4
  259. * @see http://tools.ietf.org/html/rfc6749#section-10.6
  260. * @see http://tools.ietf.org/html/rfc6749#section-4.1.3
  261. *
  262. * @ingroup oauth2_section_4
  263. */
  264. public function handleTokenRequest(RequestInterface $request, ResponseInterface $response = null)
  265. {
  266. $this->response = is_null($response) ? new Response() : $response;
  267. $this->getTokenController()->handleTokenRequest($request, $this->response);
  268. return $this->response;
  269. }
  270. public function grantAccessToken(RequestInterface $request, ResponseInterface $response = null)
  271. {
  272. $this->response = is_null($response) ? new Response() : $response;
  273. $value = $this->getTokenController()->grantAccessToken($request, $this->response);
  274. return $value;
  275. }
  276. /**
  277. * Handle a revoke token request
  278. * This would be called from the "/revoke" endpoint as defined in the draft Token Revocation spec
  279. *
  280. * @see https://tools.ietf.org/html/rfc7009#section-2
  281. *
  282. * @param RequestInterface $request
  283. * @param ResponseInterface $response
  284. * @return Response|ResponseInterface
  285. */
  286. public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response = null)
  287. {
  288. $this->response = is_null($response) ? new Response() : $response;
  289. $this->getTokenController()->handleRevokeRequest($request, $this->response);
  290. return $this->response;
  291. }
  292. /**
  293. * Redirect the user appropriately after approval.
  294. *
  295. * After the user has approved or denied the resource request the
  296. * authorization server should call this function to redirect the user
  297. * appropriately.
  298. *
  299. * @param $request
  300. * The request should have the follow parameters set in the querystring:
  301. * - response_type: The requested response: an access token, an
  302. * authorization code, or both.
  303. * - client_id: The client identifier as described in Section 2.
  304. * - redirect_uri: An absolute URI to which the authorization server
  305. * will redirect the user-agent to when the end-user authorization
  306. * step is completed.
  307. * - scope: (optional) The scope of the resource request expressed as a
  308. * list of space-delimited strings.
  309. * - state: (optional) An opaque value used by the client to maintain
  310. * state between the request and callback.
  311. * @param ResponseInterface $response
  312. * @param $is_authorized
  313. * TRUE or FALSE depending on whether the user authorized the access.
  314. * @param $user_id
  315. * Identifier of user who authorized the client
  316. *
  317. * @return Response
  318. *
  319. * @see http://tools.ietf.org/html/rfc6749#section-4
  320. *
  321. * @ingroup oauth2_section_4
  322. */
  323. public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null)
  324. {
  325. $this->response = $response;
  326. $this->getAuthorizeController()->handleAuthorizeRequest($request, $this->response, $is_authorized, $user_id);
  327. return $this->response;
  328. }
  329. /**
  330. * Pull the authorization request data out of the HTTP request.
  331. * - The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it
  332. * by setting $config['enforce_redirect'] to true.
  333. * - The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that
  334. * CSRF protection is MANDATORY. You can enforce this by setting the $config['enforce_state'] to true.
  335. *
  336. * The draft specifies that the parameters should be retrieved from GET, override the Response
  337. * object to change this
  338. *
  339. * @return
  340. * The authorization parameters so the authorization server can prompt
  341. * the user for approval if valid.
  342. *
  343. * @see http://tools.ietf.org/html/rfc6749#section-4.1.1
  344. * @see http://tools.ietf.org/html/rfc6749#section-10.12
  345. *
  346. * @ingroup oauth2_section_3
  347. */
  348. public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response = null)
  349. {
  350. $this->response = is_null($response) ? new Response() : $response;
  351. $value = $this->getAuthorizeController()->validateAuthorizeRequest($request, $this->response);
  352. return $value;
  353. }
  354. public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response = null, $scope = null)
  355. {
  356. $this->response = is_null($response) ? new Response() : $response;
  357. $value = $this->getResourceController()->verifyResourceRequest($request, $this->response, $scope);
  358. return $value;
  359. }
  360. public function getAccessTokenData(RequestInterface $request, ResponseInterface $response = null)
  361. {
  362. $this->response = is_null($response) ? new Response() : $response;
  363. $value = $this->getResourceController()->getAccessTokenData($request, $this->response);
  364. return $value;
  365. }
  366. public function addGrantType(GrantTypeInterface $grantType, $identifier = null)
  367. {
  368. if (!is_string($identifier)) {
  369. $identifier = $grantType->getQuerystringIdentifier();
  370. }
  371. $this->grantTypes[$identifier] = $grantType;
  372. // persist added grant type down to TokenController
  373. if (!is_null($this->tokenController)) {
  374. $this->getTokenController()->addGrantType($grantType, $identifier);
  375. }
  376. }
  377. /**
  378. * Set a storage object for the server
  379. *
  380. * @param $storage
  381. * An object implementing one of the Storage interfaces
  382. * @param $key
  383. * If null, the storage is set to the key of each storage interface it implements
  384. *
  385. * @see storageMap
  386. */
  387. public function addStorage($storage, $key = null)
  388. {
  389. // if explicitly set to a valid key, do not "magically" set below
  390. if (isset($this->storageMap[$key])) {
  391. if (!is_null($storage) && !$storage instanceof $this->storageMap[$key]) {
  392. throw new \InvalidArgumentException(sprintf('storage of type "%s" must implement interface "%s"', $key, $this->storageMap[$key]));
  393. }
  394. $this->storages[$key] = $storage;
  395. // special logic to handle "client" and "client_credentials" strangeness
  396. if ($key === 'client' && !isset($this->storages['client_credentials'])) {
  397. if ($storage instanceof \OAuth2\Storage\ClientCredentialsInterface) {
  398. $this->storages['client_credentials'] = $storage;
  399. }
  400. } elseif ($key === 'client_credentials' && !isset($this->storages['client'])) {
  401. if ($storage instanceof \OAuth2\Storage\ClientInterface) {
  402. $this->storages['client'] = $storage;
  403. }
  404. }
  405. } elseif (!is_null($key) && !is_numeric($key)) {
  406. throw new \InvalidArgumentException(sprintf('unknown storage key "%s", must be one of [%s]', $key, implode(', ', array_keys($this->storageMap))));
  407. } else {
  408. $set = false;
  409. foreach ($this->storageMap as $type => $interface) {
  410. if ($storage instanceof $interface) {
  411. $this->storages[$type] = $storage;
  412. $set = true;
  413. }
  414. }
  415. if (!$set) {
  416. throw new \InvalidArgumentException(sprintf('storage of class "%s" must implement one of [%s]', get_class($storage), implode(', ', $this->storageMap)));
  417. }
  418. }
  419. }
  420. public function addResponseType(ResponseTypeInterface $responseType, $key = null)
  421. {
  422. $key = $this->normalizeResponseType($key);
  423. if (isset($this->responseTypeMap[$key])) {
  424. if (!$responseType instanceof $this->responseTypeMap[$key]) {
  425. throw new \InvalidArgumentException(sprintf('responseType of type "%s" must implement interface "%s"', $key, $this->responseTypeMap[$key]));
  426. }
  427. $this->responseTypes[$key] = $responseType;
  428. } elseif (!is_null($key) && !is_numeric($key)) {
  429. throw new \InvalidArgumentException(sprintf('unknown responseType key "%s", must be one of [%s]', $key, implode(', ', array_keys($this->responseTypeMap))));
  430. } else {
  431. $set = false;
  432. foreach ($this->responseTypeMap as $type => $interface) {
  433. if ($responseType instanceof $interface) {
  434. $this->responseTypes[$type] = $responseType;
  435. $set = true;
  436. }
  437. }
  438. if (!$set) {
  439. throw new \InvalidArgumentException(sprintf('Unknown response type %s. Please implement one of [%s]', get_class($responseType), implode(', ', $this->responseTypeMap)));
  440. }
  441. }
  442. }
  443. public function getScopeUtil()
  444. {
  445. if (!$this->scopeUtil) {
  446. $storage = isset($this->storages['scope']) ? $this->storages['scope'] : null;
  447. $this->scopeUtil = new Scope($storage);
  448. }
  449. return $this->scopeUtil;
  450. }
  451. /**
  452. * every getter deserves a setter
  453. *
  454. * @param ScopeInterface $scopeUtil
  455. */
  456. public function setScopeUtil($scopeUtil)
  457. {
  458. $this->scopeUtil = $scopeUtil;
  459. }
  460. protected function createDefaultAuthorizeController()
  461. {
  462. if (!isset($this->storages['client'])) {
  463. throw new \LogicException('You must supply a storage object implementing \OAuth2\Storage\ClientInterface to use the authorize server');
  464. }
  465. if (0 == count($this->responseTypes)) {
  466. $this->responseTypes = $this->getDefaultResponseTypes();
  467. }
  468. if ($this->config['use_openid_connect'] && !isset($this->responseTypes['id_token'])) {
  469. $this->responseTypes['id_token'] = $this->createDefaultIdTokenResponseType();
  470. if ($this->config['allow_implicit']) {
  471. $this->responseTypes['id_token token'] = $this->createDefaultIdTokenTokenResponseType();
  472. }
  473. }
  474. $config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_implicit enforce_state require_exact_redirect_uri')));
  475. if ($this->config['use_openid_connect']) {
  476. return new OpenIDAuthorizeController($this->storages['client'], $this->responseTypes, $config, $this->getScopeUtil());
  477. }
  478. return new AuthorizeController($this->storages['client'], $this->responseTypes, $config, $this->getScopeUtil());
  479. }
  480. protected function createDefaultTokenController()
  481. {
  482. if (0 == count($this->grantTypes)) {
  483. $this->grantTypes = $this->getDefaultGrantTypes();
  484. }
  485. if (is_null($this->clientAssertionType)) {
  486. // see if HttpBasic assertion type is requred. If so, then create it from storage classes.
  487. foreach ($this->grantTypes as $grantType) {
  488. if (!$grantType instanceof ClientAssertionTypeInterface) {
  489. if (!isset($this->storages['client_credentials'])) {
  490. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\ClientCredentialsInterface to use the token server');
  491. }
  492. $config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_credentials_in_request_body allow_public_clients')));
  493. $this->clientAssertionType = new HttpBasic($this->storages['client_credentials'], $config);
  494. break;
  495. }
  496. }
  497. }
  498. if (!isset($this->storages['client'])) {
  499. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\ClientInterface to use the token server');
  500. }
  501. $accessTokenResponseType = $this->getAccessTokenResponseType();
  502. return new TokenController($accessTokenResponseType, $this->storages['client'], $this->grantTypes, $this->clientAssertionType, $this->getScopeUtil());
  503. }
  504. protected function createDefaultResourceController()
  505. {
  506. if ($this->config['use_jwt_access_tokens']) {
  507. // overwrites access token storage with crypto token storage if "use_jwt_access_tokens" is set
  508. if (!isset($this->storages['access_token']) || !$this->storages['access_token'] instanceof JwtAccessTokenInterface) {
  509. $this->storages['access_token'] = $this->createDefaultJwtAccessTokenStorage();
  510. }
  511. } elseif (!isset($this->storages['access_token'])) {
  512. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\AccessTokenInterface or use JwtAccessTokens to use the resource server');
  513. }
  514. if (!$this->tokenType) {
  515. $this->tokenType = $this->getDefaultTokenType();
  516. }
  517. $config = array_intersect_key($this->config, array('www_realm' => ''));
  518. return new ResourceController($this->tokenType, $this->storages['access_token'], $config, $this->getScopeUtil());
  519. }
  520. protected function createDefaultUserInfoController()
  521. {
  522. if ($this->config['use_jwt_access_tokens']) {
  523. // overwrites access token storage with crypto token storage if "use_jwt_access_tokens" is set
  524. if (!isset($this->storages['access_token']) || !$this->storages['access_token'] instanceof JwtAccessTokenInterface) {
  525. $this->storages['access_token'] = $this->createDefaultJwtAccessTokenStorage();
  526. }
  527. } elseif (!isset($this->storages['access_token'])) {
  528. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\AccessTokenInterface or use JwtAccessTokens to use the UserInfo server');
  529. }
  530. if (!isset($this->storages['user_claims'])) {
  531. throw new \LogicException('You must supply a storage object implementing OAuth2\OpenID\Storage\UserClaimsInterface to use the UserInfo server');
  532. }
  533. if (!$this->tokenType) {
  534. $this->tokenType = $this->getDefaultTokenType();
  535. }
  536. $config = array_intersect_key($this->config, array('www_realm' => ''));
  537. return new UserInfoController($this->tokenType, $this->storages['access_token'], $this->storages['user_claims'], $config, $this->getScopeUtil());
  538. }
  539. protected function getDefaultTokenType()
  540. {
  541. $config = array_intersect_key($this->config, array_flip(explode(' ', 'token_param_name token_bearer_header_name')));
  542. return new Bearer($config);
  543. }
  544. protected function getDefaultResponseTypes()
  545. {
  546. $responseTypes = array();
  547. if ($this->config['allow_implicit']) {
  548. $responseTypes['token'] = $this->getAccessTokenResponseType();
  549. }
  550. if ($this->config['use_openid_connect']) {
  551. $responseTypes['id_token'] = $this->getIdTokenResponseType();
  552. if ($this->config['allow_implicit']) {
  553. $responseTypes['id_token token'] = $this->getIdTokenTokenResponseType();
  554. }
  555. }
  556. if (isset($this->storages['authorization_code'])) {
  557. $config = array_intersect_key($this->config, array_flip(explode(' ', 'enforce_redirect auth_code_lifetime')));
  558. if ($this->config['use_openid_connect']) {
  559. if (!$this->storages['authorization_code'] instanceof OpenIDAuthorizationCodeInterface) {
  560. throw new \LogicException('Your authorization_code storage must implement OAuth2\OpenID\Storage\AuthorizationCodeInterface to work when "use_openid_connect" is true');
  561. }
  562. $responseTypes['code'] = new OpenIDAuthorizationCodeResponseType($this->storages['authorization_code'], $config);
  563. $responseTypes['code id_token'] = new CodeIdToken($responseTypes['code'], $responseTypes['id_token']);
  564. } else {
  565. $responseTypes['code'] = new AuthorizationCodeResponseType($this->storages['authorization_code'], $config);
  566. }
  567. }
  568. if (count($responseTypes) == 0) {
  569. throw new \LogicException('You must supply an array of response_types in the constructor or implement a OAuth2\Storage\AuthorizationCodeInterface storage object or set "allow_implicit" to true and implement a OAuth2\Storage\AccessTokenInterface storage object');
  570. }
  571. return $responseTypes;
  572. }
  573. protected function getDefaultGrantTypes()
  574. {
  575. $grantTypes = array();
  576. if (isset($this->storages['user_credentials'])) {
  577. $grantTypes['password'] = new UserCredentials($this->storages['user_credentials']);
  578. }
  579. if (isset($this->storages['client_credentials'])) {
  580. $config = array_intersect_key($this->config, array('allow_credentials_in_request_body' => ''));
  581. $grantTypes['client_credentials'] = new ClientCredentials($this->storages['client_credentials'], $config);
  582. }
  583. if (isset($this->storages['refresh_token'])) {
  584. $config = array_intersect_key($this->config, array_flip(explode(' ', 'always_issue_new_refresh_token unset_refresh_token_after_use')));
  585. $grantTypes['refresh_token'] = new RefreshToken($this->storages['refresh_token'], $config);
  586. }
  587. if (isset($this->storages['authorization_code'])) {
  588. if ($this->config['use_openid_connect']) {
  589. if (!$this->storages['authorization_code'] instanceof OpenIDAuthorizationCodeInterface) {
  590. throw new \LogicException('Your authorization_code storage must implement OAuth2\OpenID\Storage\AuthorizationCodeInterface to work when "use_openid_connect" is true');
  591. }
  592. $grantTypes['authorization_code'] = new OpenIDAuthorizationCodeGrantType($this->storages['authorization_code']);
  593. } else {
  594. $grantTypes['authorization_code'] = new AuthorizationCode($this->storages['authorization_code']);
  595. }
  596. }
  597. if (count($grantTypes) == 0) {
  598. throw new \LogicException('Unable to build default grant types - You must supply an array of grant_types in the constructor');
  599. }
  600. return $grantTypes;
  601. }
  602. protected function getAccessTokenResponseType()
  603. {
  604. if (isset($this->responseTypes['token'])) {
  605. return $this->responseTypes['token'];
  606. }
  607. if ($this->config['use_jwt_access_tokens']) {
  608. return $this->createDefaultJwtAccessTokenResponseType();
  609. }
  610. return $this->createDefaultAccessTokenResponseType();
  611. }
  612. protected function getIdTokenResponseType()
  613. {
  614. if (isset($this->responseTypes['id_token'])) {
  615. return $this->responseTypes['id_token'];
  616. }
  617. return $this->createDefaultIdTokenResponseType();
  618. }
  619. protected function getIdTokenTokenResponseType()
  620. {
  621. if (isset($this->responseTypes['id_token token'])) {
  622. return $this->responseTypes['id_token token'];
  623. }
  624. return $this->createDefaultIdTokenTokenResponseType();
  625. }
  626. /**
  627. * For Resource Controller
  628. */
  629. protected function createDefaultJwtAccessTokenStorage()
  630. {
  631. if (!isset($this->storages['public_key'])) {
  632. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens');
  633. }
  634. $tokenStorage = null;
  635. if (!empty($this->config['store_encrypted_token_string']) && isset($this->storages['access_token'])) {
  636. $tokenStorage = $this->storages['access_token'];
  637. }
  638. // wrap the access token storage as required.
  639. return new JwtAccessTokenStorage($this->storages['public_key'], $tokenStorage);
  640. }
  641. /**
  642. * For Authorize and Token Controllers
  643. */
  644. protected function createDefaultJwtAccessTokenResponseType()
  645. {
  646. if (!isset($this->storages['public_key'])) {
  647. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens');
  648. }
  649. $tokenStorage = null;
  650. if (isset($this->storages['access_token'])) {
  651. $tokenStorage = $this->storages['access_token'];
  652. }
  653. $refreshStorage = null;
  654. if (isset($this->storages['refresh_token'])) {
  655. $refreshStorage = $this->storages['refresh_token'];
  656. }
  657. $config = array_intersect_key($this->config, array_flip(explode(' ', 'store_encrypted_token_string issuer access_lifetime refresh_token_lifetime')));
  658. return new JwtAccessToken($this->storages['public_key'], $tokenStorage, $refreshStorage, $config);
  659. }
  660. protected function createDefaultAccessTokenResponseType()
  661. {
  662. if (!isset($this->storages['access_token'])) {
  663. throw new \LogicException('You must supply a response type implementing OAuth2\ResponseType\AccessTokenInterface, or a storage object implementing OAuth2\Storage\AccessTokenInterface to use the token server');
  664. }
  665. $refreshStorage = null;
  666. if (isset($this->storages['refresh_token'])) {
  667. $refreshStorage = $this->storages['refresh_token'];
  668. }
  669. $config = array_intersect_key($this->config, array_flip(explode(' ', 'access_lifetime refresh_token_lifetime')));
  670. $config['token_type'] = $this->tokenType ? $this->tokenType->getTokenType() : $this->getDefaultTokenType()->getTokenType();
  671. return new AccessToken($this->storages['access_token'], $refreshStorage, $config);
  672. }
  673. protected function createDefaultIdTokenResponseType()
  674. {
  675. if (!isset($this->storages['user_claims'])) {
  676. throw new \LogicException('You must supply a storage object implementing OAuth2\OpenID\Storage\UserClaimsInterface to use openid connect');
  677. }
  678. if (!isset($this->storages['public_key'])) {
  679. throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use openid connect');
  680. }
  681. $config = array_intersect_key($this->config, array_flip(explode(' ', 'issuer id_lifetime')));
  682. return new IdToken($this->storages['user_claims'], $this->storages['public_key'], $config);
  683. }
  684. protected function createDefaultIdTokenTokenResponseType()
  685. {
  686. return new IdTokenToken($this->getAccessTokenResponseType(), $this->getIdTokenResponseType());
  687. }
  688. protected function validateOpenIdConnect()
  689. {
  690. $authCodeGrant = $this->getGrantType('authorization_code');
  691. if (!empty($authCodeGrant) && !$authCodeGrant instanceof OpenIDAuthorizationCodeGrantType) {
  692. throw new \InvalidArgumentException('You have enabled OpenID Connect, but supplied a grant type that does not support it.');
  693. }
  694. }
  695. protected function normalizeResponseType($name)
  696. {
  697. // for multiple-valued response types - make them alphabetical
  698. if (!empty($name) && false !== strpos($name, ' ')) {
  699. $types = explode(' ', $name);
  700. sort($types);
  701. $name = implode(' ', $types);
  702. }
  703. return $name;
  704. }
  705. public function getResponse()
  706. {
  707. return $this->response;
  708. }
  709. public function getStorages()
  710. {
  711. return $this->storages;
  712. }
  713. public function getStorage($name)
  714. {
  715. return isset($this->storages[$name]) ? $this->storages[$name] : null;
  716. }
  717. public function getGrantTypes()
  718. {
  719. return $this->grantTypes;
  720. }
  721. public function getGrantType($name)
  722. {
  723. return isset($this->grantTypes[$name]) ? $this->grantTypes[$name] : null;
  724. }
  725. public function getResponseTypes()
  726. {
  727. return $this->responseTypes;
  728. }
  729. public function getResponseType($name)
  730. {
  731. // for multiple-valued response types - make them alphabetical
  732. $name = $this->normalizeResponseType($name);
  733. return isset($this->responseTypes[$name]) ? $this->responseTypes[$name] : null;
  734. }
  735. public function getTokenType()
  736. {
  737. return $this->tokenType;
  738. }
  739. public function getClientAssertionType()
  740. {
  741. return $this->clientAssertionType;
  742. }
  743. public function setConfig($name, $value)
  744. {
  745. $this->config[$name] = $value;
  746. }
  747. public function getConfig($name, $default = null)
  748. {
  749. return isset($this->config[$name]) ? $this->config[$name] : $default;
  750. }
  751. }