Server.php 34 KB

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