Compare commits

..

8 Commits
7.2.0 ... 5.1.x

Author SHA1 Message Date
Andrew Millington
a1a6cb7b4c Merge pull request #821 from davgothic/toggle-key-permissions-check
Add toggle to disable key permissions check for 5.1.*
2017-11-29 21:47:00 +00:00
David Hancock
696c78de58 Add toggle to disable key permissions check 2017-11-28 09:14:03 +00:00
Alex Bilbie
8e5df6d628 Updated changelog 2017-07-11 07:31:36 +01:00
Alex Bilbie
295e90c27d Trigger an E_USER_DEPRECATED notice instead of an error 2017-07-11 07:31:30 +01:00
Alex Bilbie
788ccb8605 Trigger E_USER_NOTICE instead of throwing an exception if key cannot be chmod to 600 2017-07-11 07:30:39 +01:00
Alex Bilbie
26889abdd3 5.1.4 not 5.1.14 2017-07-01 18:37:54 +01:00
Alex Bilbie
0f19a6f41c Removed HHVM from .travis.yml 2017-07-01 18:34:53 +01:00
Alex Bilbie
4e996ab3f1 Updated README 2017-07-01 18:34:32 +01:00
68 changed files with 908 additions and 1528 deletions

3
.gitattributes vendored
View File

@@ -10,5 +10,4 @@
/phpunit.xml.dist export-ignore
/CHANGELOG.md export-ignore
/CONTRIBUTING.md export-ignore
/README.md export-ignore
/README.md export-ignore

View File

@@ -29,6 +29,7 @@ enabled:
- phpdoc_inline_tag
- phpdoc_no_access
- phpdoc_no_simplified_null_return
- phpdoc_order
- phpdoc_property
- phpdoc_scalar
- phpdoc_separation

View File

@@ -1,31 +1,23 @@
language: php
dist: trusty
sudo: false
cache:
directories:
- vendor
env:
- DEPENDENCIES=""
- DEPENDENCIES="--prefer-lowest --prefer-stable"
- vendor
php:
- 5.5.9
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
install:
- composer update --no-interaction --prefer-dist $DEPENDENCIES
- travis_retry composer install --no-interaction --prefer-source
script:
- vendor/bin/phpunit --coverage-clover=coverage.clover
- vendor/bin/phpstan analyse -l 7 -c phpstan.neon src tests
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover
- vendor/bin/phpunit
branches:
only:

View File

@@ -1,467 +1,341 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## 5.1.5 (released 2017-07-11)
## [Unreleased]
To address feedback from the security release the following two changes have been made:
## [7.2.0] - released 2018-06-23
* If an RSA key cannot be `chmod`'ed to 600 then it will now throw a `E_USER_NOTICE` instead of an exception.
* Not using the new encryption key method on `AuthorizationServer` will set throw an `E_USER_DEPRECATED` message instead of an error.
### Changed
- Added new`validateRedirectUri` method AbstractGrant to remove three instances of code duplication (PR #912)
- Allow 640 as a crypt key file permission (PR #917)
## 5.1.4 (released 2017-07-01)
### Added
- Function `hasRedirect()` added to `OAuthServerException` (PR #703)
* Fixed multiple security vulnerabilities as a result of a security audit paid for by the [Mozilla Secure Open Source Fund](https://wiki.mozilla.org/MOSS/Secure_Open_Source). All users of this library are encouraged to update as soon as possible to this version or version 6.0 or greater.
* It is recommended on each `AuthorizationServer` instance you set the `setEncryptionKey()`. This will result in stronger encryption being used. If this method is not set messages will be sent to the defined error handling routines (using `error_log`). Please see the examples and documentation for examples.
* TravisCI now tests PHP 7.1 (Issue #671)
* Fix middleware example fatal error (Issue #682)
* Fix typo in the first README sentence (Issue #690)
* Corrected DateInterval from 1 min to 1 month (Issue #709)
### Fixed
- Catch and handle `BadMethodCallException` from the `verify()` method of the JWT token in the `validateAuthorization` method (PR #904)
## 5.1.3 (released 2016-10-12)
## [4.1.7] - released 2018-06-23
* Fixed WWW-Authenticate header (Issue #669)
* Increase the recommended RSA key length from 1024 to 2048 bits (Issue #668)
### Fixed
- Ensure `empty()` function call only contains variable to be compatible with PHP 5.4 (PR #918)
## 5.1.2 (released 2016-09-19)
## [7.1.1] - released 2018-05-21
* Fixed `finalizeScopes` call (Issue #650)
### Fixed
- No longer set a WWW-Authenticate header for invalid clients if the client did not send an Authorization header in the original request (PR #902)
## 5.1.1 (released 2016-07-26)
## [7.1.0] - released 2018-04-22
* Improved test suite (Issue #614)
* Updated docblocks (Issue #616)
* Replace `array_shift` with `foreach` loop (Issue #621)
* Allow easy addition of custom fields to Bearer token response (Issue #624)
* Key file auto-generation from string (Issue #625)
### Changed
- Changed hint for unsupportedGrantType exception so it no longer references the grant type parameter which isn't always expected (PR #893)
- Upgrade PHPStan checks to level 7 (PR #856)
## 5.1.0 (released 2016-06-28)
### Added
- Added event emitters for issued access and refresh tokens (PR #860)
- Can now use Defuse\Crypto\Key for encryption/decryption of keys which is faster than the Cryto class (PR #812)
* Implemented RFC7636 (Issue #574)
* Unify middleware exception responses (Issue #578)
* Updated examples (Issue #589)
* Ensure state is in access denied redirect (Issue #597)
* Remove redundant `isExpired()` method from entity interfaces and traits (Issue #600)
* Added a check for unique access token constraint violation (Issue #601)
* Look at Authorization header directly for HTTP Basic auth checks (Issue #604)
* Added catch Runtime exception when parsing JWT string (Issue #605)
* Allow `paragonie/random_compat` 2.x (Issue #606)
* Added `indigophp/hash-compat` to Composer suggestions and `require-dev` for PHP 5.5 support
### Removed
- Remove paragone/random_compat from dependencies
## 5.0.3 (released 2016-05-04)
## [7.0.0] - released 2018-02-18
* Fix hints in PasswordGrant (Issue #560)
* Add meaning of `Resource owner` to terminology.md (Issue #561)
* Use constant for event name instead of explicit string (Issue #563)
* Remove unused request property (Issue #564)
* Correct wrong phpdoc (Issue #569)
* Fixed typo in exception string (Issue #570)
### Added
- Use PHPStan for static analysis of code (PR #848)
- Enforce stricter static analysis checks and upgrade library dependencies (PR #852)
- Provide PHPStan coverage for tests and update PHPUnit (PR #849)
- Get and set methods for OAuth Server Exception payloads. Allow implementer to specify the JSON encode options (PR #719)
## 5.0.2 (released 2016-04-18)
### Changed
- ClientRepository interface will now accept null for the Grant type to improve extensibility options (PR #607)
- Do not issue an error if key file permissions are 400 or 440 (PR #839)
- Skip key file creation if the file already exists (PR #845)
- Change changelog format and update readme
* `state` parameter is now correctly returned after implicit grant authorization
* Small code and docblock improvements
### Removed
- Support for PHP 5.6
- Support for version 5.x and 6.x of the library
## 5.0.1 (released 2016-04-18)
### Fixed
- PKCE implementation (PR #744)
- Set correct redirect URI when validating scopes (PR #840)
- S256 code challenege method (PR #842)
- Accept RSA key with CRLF line endings (PR #805)
* Fixes an issue (#550) whereby it was unclear whether or not to validate a client's secret during a request.
## [6.1.1] - 2017-12-23
- Removed check on empty scopes
## [6.1.0] - 2017-12-23
- Changed the token type issued by the Implicit Grant to be Bearer instead of bearer. (PR #724)
- Replaced call to array_key_exists() with the faster isset() on the Implicit Grant. (PR #749)
- Allow specification of query delimiter character in the Password Grant (PR #801)
- Add Zend Diactoros library dependency to examples (PR #678)
- Can set default scope for the authorization endpoint. If no scope is passed during an authorization request, the default scope will be used if set. If not, the server will issue an invalid scope exception (PR #811)
- Added validation for redirect URIs on the authorization end point to ensure exactly one redirection URI has been passed (PR #573)
## [6.0.2] - 2017-08-03
- An invalid refresh token that can't be decrypted now returns a HTTP 401 error instead of HTTP 400 (Issue #759)
- Removed chmod from CryptKey and add toggle to disable checking (Issue #776)
- Fixes invalid code challenge method payload key name (Issue #777)
## [6.0.1] - 2017-07-19
To address feedback from the security release the following change has been made:
- If an RSA key cannot be chmod'ed to 600 then it will now throw a E_USER_NOTICE instead of an exception.
## [6.0.0] - 2017-07-01
- Breaking change: The `AuthorizationServer` constructor now expects an encryption key string instead of a public key
- Remove support for HHVM
- Remove support for PHP 5.5
## [5.1.4] - 2017-07-01
- Fixed multiple security vulnerabilities as a result of a security audit paid for by the [Mozilla Secure Open Source Fund](https://wiki.mozilla.org/MOSS/Secure_Open_Source). All users of this library are encouraged to update as soon as possible to this version or version 6.0 or greater.
- It is recommended on each `AuthorizationServer` instance you set the `setEncryptionKey()`. This will result in stronger encryption being used. If this method is not set messages will be sent to the defined error handling routines (using `error_log`). Please see the examples and documentation for examples.
- TravisCI now tests PHP 7.1 (Issue #671)
- Fix middleware example fatal error (Issue #682)
- Fix typo in the first README sentence (Issue #690)
- Corrected DateInterval from 1 min to 1 month (Issue #709)
## [5.1.3] - 2016-10-12
- Fixed WWW-Authenticate header (Issue #669)
- Increase the recommended RSA key length from 1024 to 2048 bits (Issue #668)
## [5.1.2] - 2016-09-19
- Fixed `finalizeScopes` call (Issue #650)
## [4.1.6] - 2016-09-13
- Less restrictive on Authorization header check (Issue #652)
## [5.1.1] - 2016-07-26
- Improved test suite (Issue #614)
- Updated docblocks (Issue #616)
- Replace `array_shift` with `foreach` loop (Issue #621)
- Allow easy addition of custom fields to Bearer token response (Issue #624)
- Key file auto-generation from string (Issue #625)
## [5.1.0] - 2016-06-28
- Implemented RFC7636 (Issue #574)
- Unify middleware exception responses (Issue #578)
- Updated examples (Issue #589)
- Ensure state is in access denied redirect (Issue #597)
- Remove redundant `isExpired()` method from entity interfaces and traits (Issue #600)
- Added a check for unique access token constraint violation (Issue #601)
- Look at Authorization header directly for HTTP Basic auth checks (Issue #604)
- Added catch Runtime exception when parsing JWT string (Issue #605)
- Allow `paragonie/random_compat` 2.x (Issue #606)
- Added `indigophp/hash-compat` to Composer suggestions and `require-dev` for PHP 5.5 support
## [5.0.3] - 2016-05-04
- Fix hints in PasswordGrant (Issue #560)
- Add meaning of `Resource owner` to terminology.md (Issue #561)
- Use constant for event name instead of explicit string (Issue #563)
- Remove unused request property (Issue #564)
- Correct wrong phpdoc (Issue #569)
- Fixed typo in exception string (Issue #570)
## [5.0.2] - 2016-04-18
- `state` parameter is now correctly returned after implicit grant authorization
- Small code and docblock improvements
## [5.0.1] - 2016-04-18
- Fixes an issue (#550) whereby it was unclear whether or not to validate a client's secret during a request.
## [5.0.0] - 2016-04-17
## 5.0.0 (released 2016-04-17)
Version 5 is a complete code rewrite.
- Renamed Server class to AuthorizationServer
- Added ResourceServer class
- Run unit tests again PHP 5.5.9 as it's the minimum supported version
- Enable PHPUnit 5.0 support
- Improved examples and documentation
- Make it clearer that the implicit grant doesn't support refresh tokens
- Improved refresh token validation errors
- Fixed refresh token expiry date
* JWT support
* PSR-7 support
* Improved exception errors
* Replace all occurrences of the term "Storage" with "Repository"
* Simplify repositories
* Entities conform to interfaces and use traits
* Auth code grant updated
* Allow support for public clients
* Add support for #439
* Client credentials grant updated
* Password grant updated
* Allow support for public clients
* Refresh token grant updated
* Implement Implicit grant
* Bearer token output type
* Remove MAC token output type
* Authorization server rewrite
* Resource server class moved to PSR-7 middleware
* Tests
* Much much better documentation
## [5.0.0-RC2] - 2016-04-10
Changes since RC2:
- Allow multiple client redirect URIs (Issue #511)
- Remove unused mac token interface (Issue #503)
- Handle RSA key passphrase (Issue #502)
- Remove access token repository from response types (Issue #501)
- Remove unnecessary methods from entity interfaces (Issue #490)
- Ensure incoming JWT hasn't expired (Issue #509)
- Fix client identifier passed where user identifier is expected (Issue #498)
- Removed built-in entities; added traits to for quick re-use (Issue #504)
- Redirect uri is required only if the "redirect_uri" parameter was included in the authorization request (Issue #514)
- Removed templating for auth code and implicit grants (Issue #499)
* Renamed Server class to AuthorizationServer
* Added ResourceServer class
* Run unit tests again PHP 5.5.9 as it's the minimum supported version
* Enable PHPUnit 5.0 support
* Improved examples and documentation
* Make it clearer that the implicit grant doesn't support refresh tokens
* Improved refresh token validation errors
* Fixed refresh token expiry date
## [5.0.0-RC1] - 2016-03-24
## 5.0.0-RC2 (released 2016-04-10)
Changes since RC1:
* Allow multiple client redirect URIs (Issue #511)
* Remove unused mac token interface (Issue #503)
* Handle RSA key passphrase (Issue #502)
* Remove access token repository from response types (Issue #501)
* Remove unnecessary methods from entity interfaces (Issue #490)
* Ensure incoming JWT hasn't expired (Issue #509)
* Fix client identifier passed where user identifier is expected (Issue #498)
* Removed built-in entities; added traits to for quick re-use (Issue #504)
* Redirect uri is required only if the "redirect_uri" parameter was included in the authorization request (Issue #514)
* Removed templating for auth code and implicit grants (Issue #499)
## 5.0.0-RC1 (release 2016-03-24)
Version 5 is a complete code rewrite.
- JWT support
- PSR-7 support
- Improved exception errors
- Replace all occurrences of the term "Storage" with "Repository"
- Simplify repositories
- Entities conform to interfaces and use traits
- Auth code grant updated
- Allow support for public clients
- Add support for #439
- Client credentials grant updated
- Password grant updated
- Allow support for public clients
- Refresh token grant updated
- Implement Implicit grant
- Bearer token output type
- Remove MAC token output type
- Authorization server rewrite
- Resource server class moved to PSR-7 middleware
- Tests
- Much much better documentation
* JWT support
* PSR-7 support
* Improved exception errors
* Replace all occurrences of the term "Storage" with "Repository"
* Simplify repositories
* Entities conform to interfaces and use traits
* Auth code grant updated
* Allow support for public clients
* Add support for #439
* Client credentials grant updated
* Password grant updated
* Allow support for public clients
* Refresh token grant updated
* Implement Implicit grant
* Bearer token output type
* Remove MAC token output type
* Authorization server rewrite
* Resource server class moved to PSR-7 middleware
* Tests
* Much much better documentation
## [4.1.5] - 2016-01-04
## 4.1.5 (released 2016-01-04)
- Enable Symfony 3.0 support (#412)
* Enable Symfony 3.0 support (#412)
## [4.1.4] - 2015-11-13
## 4.1.4 (released 2015-11-13)
- Fix for determining access token in header (Issue #328)
- Refresh tokens are now returned for MAC responses (Issue #356)
- Added integration list to readme (Issue #341)
- Expose parameter passed to exceptions (Issue #345)
- Removed duplicate routing setup code (Issue #346)
- Docs fix (Issues #347, #360, #380)
- Examples fix (Issues #348, #358)
- Fix typo in docblock (Issue #352)
- Improved timeouts for MAC tokens (Issue #364)
- `hash_hmac()` should output raw binary data, not hexits (Issue #370)
- Improved regex for matching all Base64 characters (Issue #371)
- Fix incorrect signature parameter (Issue #372)
- AuthCodeGrant and RefreshTokenGrant don't require client_secret (Issue #377)
- Added priority argument to event listener (Issue #388)
* Fix for determining access token in header (Issue #328)
* Refresh tokens are now returned for MAC responses (Issue #356)
* Added integration list to readme (Issue #341)
* Expose parameter passed to exceptions (Issue #345)
* Removed duplicate routing setup code (Issue #346)
* Docs fix (Issues #347, #360, #380)
* Examples fix (Issues #348, #358)
* Fix typo in docblock (Issue #352)
* Improved timeouts for MAC tokens (Issue #364)
* `hash_hmac()` should output raw binary data, not hexits (Issue #370)
* Improved regex for matching all Base64 characters (Issue #371)
* Fix incorrect signature parameter (Issue #372)
* AuthCodeGrant and RefreshTokenGrant don't require client_secret (Issue #377)
* Added priority argument to event listener (Issue #388)
## [4.1.3] - 2015-03-22
## 4.1.3 (released 2015-03-22)
- Docblock, namespace and inconsistency fixes (Issue #303)
- Docblock type fix (Issue #310)
- Example bug fix (Issue #300)
- Updated league/event to ~2.1 (Issue #311)
- Fixed missing session scope (Issue #319)
- Updated interface docs (Issue #323)
- `.travis.yml` updates
* Docblock, namespace and inconsistency fixes (Issue #303)
* Docblock type fix (Issue #310)
* Example bug fix (Issue #300)
* Updated league/event to ~2.1 (Issue #311)
* Fixed missing session scope (Issue #319)
* Updated interface docs (Issue #323)
* `.travis.yml` updates
## [4.1.2] - 2015-01-01
## 4.1.2 (released 2015-01-01)
- Remove side-effects in hash_equals() implementation (Issue #290)
* Remove side-effects in hash_equals() implementation (Issue #290)
## [4.1.1] - 2014-12-31
## 4.1.1 (released 2014-12-31)
- Changed `symfony/http-foundation` dependency version to `~2.4` so package can be installed in Laravel `4.1.*`
* Changed `symfony/http-foundation` dependency version to `~2.4` so package can be installed in Laravel `4.1.*`
## [4.1.0] - 2014-12-27
## 4.1.0 (released 2014-12-27)
- Added MAC token support (Issue #158)
- Fixed example init code (Issue #280)
- Toggle refresh token rotation (Issue #286)
- Docblock fixes
* Added MAC token support (Issue #158)
* Fixed example init code (Issue #280)
* Toggle refresh token rotation (Issue #286)
* Docblock fixes
## [4.0.5] - 2014-12-15
## 4.0.5 (released 2014-12-15)
- Prevent duplicate session in auth code grant (Issue #282)
* Prevent duplicate session in auth code grant (Issue #282)
## [4.0.4] - 2014-12-03
## 4.0.4 (released 2014-12-03)
- Ensure refresh token hasn't expired (Issue #270)
* Ensure refresh token hasn't expired (Issue #270)
## [4.0.3] - 2014-12-02
## 4.0.3 (released 2014-12-02)
- Fix bad type hintings (Issue #267)
- Do not forget to set the expire time (Issue #268)
* Fix bad type hintings (Issue #267)
* Do not forget to set the expire time (Issue #268)
## [4.0.2] - 2014-11-21
## 4.0.2 (released 2014-11-21)
- Improved interfaces (Issue #255)
- Learnt how to spell delimiter and so `getScopeDelimiter()` and `setScopeDelimiter()` methods have been renamed
- Docblock improvements (Issue #254)
* Improved interfaces (Issue #255)
* Learnt how to spell delimiter and so `getScopeDelimiter()` and `setScopeDelimiter()` methods have been renamed
* Docblock improvements (Issue #254)
## [4.0.1] - 2014-11-09
## 4.0.1 (released 2014-11-09)
- Alias the master branch in composer.json (Issue #243)
- Numerous PHP CodeSniffer fixes (Issue #244)
- .travis.yml update (Issue #245)
- The getAccessToken method should return an AccessTokenEntity object instead of a string in ResourceServer.php (#246)
* Alias the master branch in composer.json (Issue #243)
* Numerous PHP CodeSniffer fixes (Issue #244)
* .travis.yml update (Issue #245)
* The getAccessToken method should return an AccessTokenEntity object instead of a string in ResourceServer.php (#246)
## [4.0.0] - 2014-11-08
## 4.0.0 (released 2014-11-08)
- Complete rewrite
- Check out the documentation - [http://oauth2.thephpleague.com](http://oauth2.thephpleague.com)
* Complete rewrite
* Check out the documentation - [http://oauth2.thephpleague.com](http://oauth2.thephpleague.com)
## [3.2.0] - 2014-04-16
## 3.2.0 (released 2014-04-16)
- Added the ability to change the algorithm that is used to generate the token strings (Issue #151)
* Added the ability to change the algorithm that is used to generate the token strings (Issue #151)
## [3.1.2] - 2014-02-26
## 3.1.2 (released 2014-02-26)
- Support Authorization being an environment variable. [See more](http://fortrabbit.com/docs/essentials/quirks-and-constraints#authorization-header)
* Support Authorization being an environment variable. [See more](http://fortrabbit.com/docs/essentials/quirks-and-constraints#authorization-header)
## [3.1.1] - 2013-12-05
## 3.1.1 (released 2013-12-05)
- Normalize headers when `getallheaders()` is available (Issues #108 and #114)
* Normalize headers when `getallheaders()` is available (Issues #108 and #114)
## [3.1.0] - 2013-12-05
## 3.1.0 (released 2013-12-05)
- No longer necessary to inject the authorisation server into a grant, the server will inject itself
- Added test for 1419ba8cdcf18dd034c8db9f7de86a2594b68605
* No longer necessary to inject the authorisation server into a grant, the server will inject itself
* Added test for 1419ba8cdcf18dd034c8db9f7de86a2594b68605
## [3.0.1] - 2013-12-02
## 3.0.1 (released 2013-12-02)
- Forgot to tell TravisCI from testing PHP 5.3
* Forgot to tell TravisCI from testing PHP 5.3
## [3.0.0] - 2013-12-02
## 3.0.0 (released 2013-12-02)
- Fixed spelling of Implicit grant class (Issue #84)
- Travis CI now tests for PHP 5.5
- Fixes for checking headers for resource server (Issues #79 and #)
- The word "bearer" now has a capital "B" in JSON output to match OAuth 2.0 spec
- All grants no longer remove old sessions by default
- All grants now support custom access token TTL (Issue #92)
- All methods which didn't before return a value now return `$this` to support method chaining
- Removed the build in DB providers - these will be put in their own repos to remove baggage in the main repository
- Removed support for PHP 5.3 because this library now uses traits and will use other modern PHP features going forward
- Moved some grant related functions into a trait to reduce duplicate code
* Fixed spelling of Implicit grant class (Issue #84)
* Travis CI now tests for PHP 5.5
* Fixes for checking headers for resource server (Issues #79 and #)
* The word "bearer" now has a capital "B" in JSON output to match OAuth 2.0 spec
* All grants no longer remove old sessions by default
* All grants now support custom access token TTL (Issue #92)
* All methods which didn't before return a value now return `$this` to support method chaining
* Removed the build in DB providers - these will be put in their own repos to remove baggage in the main repository
* Removed support for PHP 5.3 because this library now uses traits and will use other modern PHP features going forward
* Moved some grant related functions into a trait to reduce duplicate code
## [2.1.1] - 2013-06-02
## 2.1.1 (released 2013-06-02)
- Added conditional `isValid()` flag to check for Authorization header only (thanks @alexmcroberts)
- Fixed semantic meaning of `requireScopeParam()` and `requireStateParam()` by changing their default value to true
- Updated some duff docblocks
- Corrected array key call in Resource.php (Issue #63)
* Added conditional `isValid()` flag to check for Authorization header only (thanks @alexmcroberts)
* Fixed semantic meaning of `requireScopeParam()` and `requireStateParam()` by changing their default value to true
* Updated some duff docblocks
* Corrected array key call in Resource.php (Issue #63)
## [2.1.0] - 2013-05-10
## 2.1 (released 2013-05-10)
- Moved zetacomponents/database to "suggest" in composer.json. If you rely on this feature you now need to include " zetacomponents/database" into "require" key in your own composer.json. (Issue #51)
- New method in Refresh grant called `rotateRefreshTokens()`. Pass in `true` to issue a new refresh token each time an access token is refreshed. This parameter needs to be set to true in order to request reduced scopes with the new access token. (Issue #47)
- Rename `key` column in oauth_scopes table to `scope` as `key` is a reserved SQL word. (Issue #45)
- The `scope` parameter is no longer required by default as per the RFC. (Issue #43)
- You can now set multiple default scopes by passing an array into `setDefaultScope()`. (Issue #42)
- The password and client credentials grants now allow for multiple sessions per user. (Issue #32)
- Scopes associated to authorization codes are not held in their own table (Issue #44)
- Database schema updates.
* Moved zetacomponents/database to "suggest" in composer.json. If you rely on this feature you now need to include " zetacomponents/database" into "require" key in your own composer.json. (Issue #51)
* New method in Refresh grant called `rotateRefreshTokens()`. Pass in `true` to issue a new refresh token each time an access token is refreshed. This parameter needs to be set to true in order to request reduced scopes with the new access token. (Issue #47)
* Rename `key` column in oauth_scopes table to `scope` as `key` is a reserved SQL word. (Issue #45)
* The `scope` parameter is no longer required by default as per the RFC. (Issue #43)
* You can now set multiple default scopes by passing an array into `setDefaultScope()`. (Issue #42)
* The password and client credentials grants now allow for multiple sessions per user. (Issue #32)
* Scopes associated to authorization codes are not held in their own table (Issue #44)
* Database schema updates.
## [2.0.5] - 2013-05-09
## 2.0.5 (released 2013-05-09)
- Fixed `oauth_session_token_scopes` table primary key
- Removed `DEFAULT ''` that has slipped into some tables
- Fixed docblock for `SessionInterface::associateRefreshToken()`
* Fixed `oauth_session_token_scopes` table primary key
* Removed `DEFAULT ''` that has slipped into some tables
* Fixed docblock for `SessionInterface::associateRefreshToken()`
## [2.0.4] - 2013-05-09
## 2.0.4 (released 2013-05-09)
- Renamed primary key in oauth_client_endpoints table
- Adding missing column to oauth_session_authcodes
* Renamed primary key in oauth_client_endpoints table
* Adding missing column to oauth_session_authcodes
* SECURITY FIX: A refresh token should be bound to a client ID
### Security
- A refresh token should be bound to a client ID
## 2.0.3 (released 2013-05-08)
## [2.0.3] - 2013-05-08
* Fixed a link to code in composer.json
- Fixed a link to code in composer.json
## 2.0.2 (released 2013-05-08)
## [2.0.2] - 2013-05-08
* Updated README with wiki guides
* Removed `null` as default parameters in some methods in the storage interfaces
* Fixed license copyright
- Updated README with wiki guides
- Removed `null` as default parameters in some methods in the storage interfaces
- Fixed license copyright
## [2.0.0] - 2013-05-08
## 2.0.0 (released 2013-05-08)
**If you're upgrading from v1.0.8 there are lots of breaking changes**
- Rewrote the session storage interface from scratch so methods are more obvious
- Included a PDO driver which implements the storage interfaces so the library is more "get up and go"
- Further normalised the database structure so all sessions no longer contain infomation related to authorization grant (which may or may not be enabled)
- A session can have multiple associated access tokens
- Individual grants can have custom expire times for access tokens
- Authorization codes now have a TTL of 10 minutes by default (can be manually set)
- Refresh tokens now have a TTL of one week by default (can be manually set)
- The client credentials grant will no longer gives out refresh tokens as per the specification
* Rewrote the session storage interface from scratch so methods are more obvious
* Included a PDO driver which implements the storage interfaces so the library is more "get up and go"
* Further normalised the database structure so all sessions no longer contain infomation related to authorization grant (which may or may not be enabled)
* A session can have multiple associated access tokens
* Individual grants can have custom expire times for access tokens
* Authorization codes now have a TTL of 10 minutes by default (can be manually set)
* Refresh tokens now have a TTL of one week by default (can be manually set)
* The client credentials grant will no longer gives out refresh tokens as per the specification
## [1.0.8] - 2013-03-18
## 1.0.8 (released 2013-03-18)
- Fixed check for required state parameter
- Fixed check that user's credentials are correct in Password grant
* Fixed check for required state parameter
* Fixed check that user's credentials are correct in Password grant
## [1.0.7] - 2013-03-04
## 1.0.7 (released 2013-03-04)
- Added method `requireStateParam()`
- Added method `requireScopeParam()`
* Added method `requireStateParam()`
* Added method `requireScopeParam()`
## [1.0.6] - 2013-02-22
## 1.0.6 (released 2013-02-22)
- Added links to tutorials in the README
- Added missing `state` parameter request to the `checkAuthoriseParams()` method.
* Added links to tutorials in the README
* Added missing `state` parameter request to the `checkAuthoriseParams()` method.
## [1.0.5] - 2013-02-21
## 1.0.5 (released 2013-02-21)
- Fixed the SQL example for SessionInterface::getScopes()
* Fixed the SQL example for SessionInterface::getScopes()
## [1.0.3] - 2013-02-20
## 1.0.3 (released 2013-02-20)
- Changed all instances of the "authentication server" to "authorization server"
* Changed all instances of the "authentication server" to "authorization server"
## [1.0.2] - 2013-02-20
## 1.0.2 (released 2013-02-20)
- Fixed MySQL create table order
- Fixed version number in composer.json
* Fixed MySQL create table order
* Fixed version number in composer.json
## [1.0.1] - 2013-02-19
## 1.0.1 (released 2013-02-19)
- Updated AuthServer.php to use `self::getParam()`
* Updated AuthServer.php to use `self::getParam()`
## 1.0.0 - 2013-02-15
## 1.0.0 (released 2013-02-15)
- First major release
[Unreleased]: https://github.com/thephpleague/oauth2-server/compare/7.2.0...HEAD
[7.2.0]: https://github.com/thephpleague/oauth2-server/compare/7.1.1...7.2.0
[7.1.1]: https://github.com/thephpleague/oauth2-server/compare/7.1.0...7.1.1
[7.1.0]: https://github.com/thephpleague/oauth2-server/compare/7.0.0...7.1.0
[7.0.0]: https://github.com/thephpleague/oauth2-server/compare/6.1.1...7.0.0
[6.1.1]: https://github.com/thephpleague/oauth2-server/compare/6.0.0...6.1.1
[6.1.0]: https://github.com/thephpleague/oauth2-server/compare/6.0.2...6.1.0
[6.0.2]: https://github.com/thephpleague/oauth2-server/compare/6.0.1...6.0.2
[6.0.1]: https://github.com/thephpleague/oauth2-server/compare/6.0.0...6.0.1
[6.0.0]: https://github.com/thephpleague/oauth2-server/compare/5.1.4...6.0.0
[5.1.4]: https://github.com/thephpleague/oauth2-server/compare/5.1.3...5.1.4
[5.1.3]: https://github.com/thephpleague/oauth2-server/compare/5.1.2...5.1.3
[5.1.2]: https://github.com/thephpleague/oauth2-server/compare/5.1.1...5.1.2
[5.1.1]: https://github.com/thephpleague/oauth2-server/compare/5.1.0...5.1.1
[5.1.0]: https://github.com/thephpleague/oauth2-server/compare/5.0.2...5.1.0
[5.0.3]: https://github.com/thephpleague/oauth2-server/compare/5.0.3...5.0.2
[5.0.2]: https://github.com/thephpleague/oauth2-server/compare/5.0.1...5.0.2
[5.0.1]: https://github.com/thephpleague/oauth2-server/compare/5.0.0...5.0.1
[5.0.0]: https://github.com/thephpleague/oauth2-server/compare/5.0.0-RC2...5.0.0
[5.0.0-RC2]: https://github.com/thephpleague/oauth2-server/compare/5.0.0-RC1...5.0.0-RC2
[5.0.0-RC1]: https://github.com/thephpleague/oauth2-server/compare/4.1.5...5.0.0-RC1
[4.1.7]: https://github.com/thephpleague/oauth2-server/compare/4.1.6...4.1.7
[4.1.6]: https://github.com/thephpleague/oauth2-server/compare/4.1.5...4.1.6
[4.1.5]: https://github.com/thephpleague/oauth2-server/compare/4.1.4...4.1.5
[4.1.4]: https://github.com/thephpleague/oauth2-server/compare/4.1.3...4.1.4
[4.1.3]: https://github.com/thephpleague/oauth2-server/compare/4.1.2...4.1.3
[4.1.2]: https://github.com/thephpleague/oauth2-server/compare/4.1.1...4.1.2
[4.1.1]: https://github.com/thephpleague/oauth2-server/compare/4.0.0...4.1.1
[4.1.0]: https://github.com/thephpleague/oauth2-server/compare/4.0.5...4.1.0
[4.0.5]: https://github.com/thephpleague/oauth2-server/compare/4.0.4...4.0.5
[4.0.4]: https://github.com/thephpleague/oauth2-server/compare/4.0.3...4.0.4
[4.0.3]: https://github.com/thephpleague/oauth2-server/compare/4.0.2...4.0.3
[4.0.2]: https://github.com/thephpleague/oauth2-server/compare/4.0.1...4.0.2
[4.0.1]: https://github.com/thephpleague/oauth2-server/compare/4.0.0...4.0.1
[4.0.0]: https://github.com/thephpleague/oauth2-server/compare/3.2.0...4.0.0
[3.2.0]: https://github.com/thephpleague/oauth2-server/compare/3.1.2...3.2.0
[3.1.2]: https://github.com/thephpleague/oauth2-server/compare/3.1.1...3.1.2
[3.1.1]: https://github.com/thephpleague/oauth2-server/compare/3.1.0...3.1.1
[3.1.0]: https://github.com/thephpleague/oauth2-server/compare/3.0.1...3.1.0
[3.0.1]: https://github.com/thephpleague/oauth2-server/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/thephpleague/oauth2-server/compare/2.1.1...3.0.0
[2.1.1]: https://github.com/thephpleague/oauth2-server/compare/2.1.0...2.1.1
[2.1.0]: https://github.com/thephpleague/oauth2-server/compare/2.0.5...2.1.0
[2.0.5]: https://github.com/thephpleague/oauth2-server/compare/2.0.4...2.0.5
[2.0.4]: https://github.com/thephpleague/oauth2-server/compare/2.0.3...2.0.4
[2.0.3]: https://github.com/thephpleague/oauth2-server/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/thephpleague/oauth2-server/compare/2.0.0...2.0.2
[2.0.0]: https://github.com/thephpleague/oauth2-server/compare/1.0.8...2.0.0
[1.0.8]: https://github.com/thephpleague/oauth2-server/compare/1.0.7...1.0.8
[1.0.7]: https://github.com/thephpleague/oauth2-server/compare/1.0.6...1.0.7
[1.0.6]: https://github.com/thephpleague/oauth2-server/compare/1.0.5...1.0.6
[1.0.5]: https://github.com/thephpleague/oauth2-server/compare/1.0.3...1.0.5
[1.0.3]: https://github.com/thephpleague/oauth2-server/compare/1.0.2...1.0.3
[1.0.2]: https://github.com/thephpleague/oauth2-server/compare/1.0.1...1.0.2
[1.0.1]: https://github.com/thephpleague/oauth2-server/compare/1.0.0...1.0.1
* First major release

View File

@@ -1,73 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race,
religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at andrew@noexceptions.io. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org

22
CONDUCT.md Normal file
View File

@@ -0,0 +1,22 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community in a direct capacity. Personal views, beliefs and values of individuals do not necessarily reflect those of the organisation or affiliated individuals and organisations.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)

View File

@@ -1,7 +1,7 @@
Thanks for contributing to this project.
**Please submit your pull request against the `master` branch only.**
**Please submit your pull request against the `develop` branch only.**
Please ensure that you run `phpunit` from the project root after you've made any changes.

View File

@@ -1,16 +1,21 @@
# PHP OAuth 2.0 Server
### :warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning:
### Security Notice
### Please upgrade to version `>=5.1.4` (backwards compatible) or `6.x` (one tiny breaking change) to fix some potential security vulnerabilities
### :warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning:
[![Latest Version](http://img.shields.io/packagist/v/league/oauth2-server.svg?style=flat-square)](https://github.com/thephpleague/oauth2-server/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Build Status](https://img.shields.io/travis/thephpleague/oauth2-server/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/oauth2-server)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/oauth2-server.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-server/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/oauth2-server.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-server)
[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-server.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-server)
[![PHPStan](https://img.shields.io/badge/PHPStan-enabled-brightgreen.svg?style=flat-square)](https://github.com/phpstan/phpstan)
`league/oauth2-server` is a standards compliant implementation of an [OAuth 2.0](https://tools.ietf.org/html/rfc6749) authorization server written in PHP which makes working with OAuth 2.0 trivial. You can easily configure an OAuth 2.0 server to protect your API with access tokens, or allow clients to request new access tokens and refresh them.
Out of the box it supports the following grants:
It supports out of the box the following grants:
* Authorization code grant
* Implicit grant
@@ -31,51 +36,26 @@ This library was created by Alex Bilbie. Find him on Twitter at [@alexbilbie](ht
The following versions of PHP are supported:
* PHP 5.5 (>=5.5.9)
* PHP 5.6
* PHP 7.0
* PHP 7.1
* PHP 7.2
* HHVM
The `openssl` extension is also required.
All HTTP messages passed to the server should be [PSR-7 compliant](https://www.php-fig.org/psr/psr-7/). This ensures interoperability with other packages and frameworks.
## Installation
```
composer require league/oauth2-server
```
## Documentation
The library documentation can be found at [https://oauth2.thephpleague.com](https://oauth2.thephpleague.com).
The library documentation can be found at [https://oauth2.thephpleague.com](https://oauth2.thephpleague.com).
You can contribute to the documentation in the [gh-pages branch](https://github.com/thephpleague/oauth2-server/tree/gh-pages/).
## Testing
The library uses [PHPUnit](https://phpunit.de/) for unit tests and [PHPStan](https://github.com/phpstan/phpstan) for static analysis of the code.
```
vendor/bin/phpunit
vendor/bin/phpstan analyse -l 7 -c phpstan.neon src tests
```
## Continous Integration
We use [Travis CI](https://travis-ci.org/), [Scrutinizer](https://scrutinizer-ci.com/), and [StyleCI](https://styleci.io/) for continuous integration. Check out [our](https://github.com/thephpleague/oauth2-server/blob/master/.travis.yml) [configuration](https://github.com/thephpleague/oauth2-server/blob/master/.scrutinizer.yml) [files](https://github.com/thephpleague/oauth2-server/blob/master/.styleci.yml) if you'd like to know more.
## Community Integrations
* [Drupal](https://www.drupal.org/project/simple_oauth)
* [Laravel Passport](https://github.com/laravel/passport)
* [OAuth 2 Server for CakePHP 3](https://github.com/uafrica/oauth-server)
## Changelog
See the [project changelog](https://github.com/thephpleague/oauth2-server/blob/master/CHANGELOG.md)
[See the project releases page](https://github.com/thephpleague/oauth2-server/releases)
## Contributing
Contributions are always welcome. Please see [CONTRIBUTING.md](https://github.com/thephpleague/oauth2-server/blob/master/CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](https://github.com/thephpleague/oauth2-server/blob/master/CODE_OF_CONDUCT.md) for details.
Please see [CONTRIBUTING.md](https://github.com/thephpleague/oauth2-server/blob/master/CONTRIBUTING.md) and [CONDUCT.md](https://github.com/thephpleague/oauth2-server/blob/master/CONDUCT.md) for details.
## Support
@@ -97,11 +77,7 @@ This package is released under the MIT License. See the bundled [LICENSE](https:
## Credits
This code is principally developed and maintained by [Andy Millington](https://twitter.com/Sephster) and [Simon Hamp](https://twitter.com/simonhamp).
Between 2012 and 2017 this library was developed and maintained by [Alex Bilbie](https://alexbilbie.com/).
PHP OAuth 2.0 Server is one of many packages provided by The PHP League. To find out more, please visit [our website](https://thephpleague.com).
This code is principally developed and maintained by [Alex Bilbie](https://twitter.com/alexbilbie).
Special thanks to [all of these awesome contributors](https://github.com/thephpleague/oauth2-server/contributors).

View File

@@ -4,19 +4,18 @@
"homepage": "https://oauth2.thephpleague.com/",
"license": "MIT",
"require": {
"php": ">=7.0.0",
"php": ">=5.5.9",
"ext-openssl": "*",
"league/event": "^2.1",
"lcobucci/jwt": "^3.2.2",
"psr/http-message": "^1.0.1",
"lcobucci/jwt": "^3.1",
"paragonie/random_compat": "^2.0",
"psr/http-message": "^1.0",
"defuse/php-encryption": "^2.1"
},
"require-dev": {
"phpunit/phpunit": "^6.3 || ^7.0",
"zendframework/zend-diactoros": "^1.3.2",
"phpstan/phpstan": "^0.9.2",
"phpstan/phpstan-phpunit": "^0.9.4",
"phpstan/phpstan-strict-rules": "^0.9.0"
"phpunit/phpunit": "^4.8 || ^5.0",
"zendframework/zend-diactoros": "^1.0",
"indigophp/hash-compat": "^1.1"
},
"repositories": [
{
@@ -61,5 +60,13 @@
"psr-4": {
"LeagueTests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-V5-WIP": "5.0-dev"
}
},
"suggest": {
"indigophp/hash-compat": "Polyfill for hash_equals function for PHP 5.5"
}
}

View File

@@ -7,8 +7,7 @@
"lcobucci/jwt": "^3.1",
"paragonie/random_compat": "^2.0",
"psr/http-message": "^1.0",
"defuse/php-encryption": "^2.1",
"zendframework/zend-diactoros": "^1.0"
"defuse/php-encryption": "^2.1"
},
"autoload": {
"psr-4": {

View File

@@ -49,18 +49,16 @@ $app->get(
],
];
$totalUsers = count($users);
// If the access token doesn't have the `basic` scope hide users' names
if (in_array('basic', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < $totalUsers; $i++) {
for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['name']);
}
}
// If the access token doesn't have the `email` scope hide users' email addresses
if (in_array('email', $request->getAttribute('oauth_scopes')) === false) {
for ($i = 0; $i < $totalUsers; $i++) {
for ($i = 0; $i < count($users); $i++) {
unset($users[$i]['email']);
}
}

View File

@@ -36,6 +36,7 @@ $app = new App([
$refreshTokenRepository = new RefreshTokenRepository();
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
$server = new AuthorizationServer(
@@ -43,8 +44,9 @@ $app = new App([
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
$publicKeyPath
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
// Enable the authentication code grant on the server with a token TTL of 1 hour
$server->enableGrantType(

View File

@@ -32,6 +32,7 @@ $app = new App([
// Path to public and private keys
$privateKey = 'file://' . __DIR__ . '/../private.key';
//$privateKey = new CryptKey('file://path/to/private.key', 'passphrase'); // if private key has a pass phrase
$publicKey = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
$server = new AuthorizationServer(
@@ -39,8 +40,9 @@ $app = new App([
$accessTokenRepository,
$scopeRepository,
$privateKey,
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
$publicKey
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
// Enable the client credentials grant on the server
$server->enableGrantType(

View File

@@ -32,6 +32,7 @@ $app = new App([
$accessTokenRepository = new AccessTokenRepository();
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
$server = new AuthorizationServer(
@@ -39,8 +40,9 @@ $app = new App([
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
$publicKeyPath
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
// Enable the implicit grant on the server with a token TTL of 1 hour
$server->enableGrantType(new ImplicitGrant(new \DateInterval('PT1H')));

View File

@@ -38,6 +38,7 @@ $app = new App([
$refreshTokenRepository = new RefreshTokenRepository();
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
$server = new AuthorizationServer(
@@ -45,8 +46,9 @@ $app = new App([
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
$publicKeyPath
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
// Enable the authentication code grant on the server with a token TTL of 1 hour
$server->enableGrantType(

View File

@@ -24,8 +24,9 @@ $app = new App([
new AccessTokenRepository(), // instance of AccessTokenRepositoryInterface
new ScopeRepository(), // instance of ScopeRepositoryInterface
'file://' . __DIR__ . '/../private.key', // path to private key
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen' // encryption key
'file://' . __DIR__ . '/../public.key' // path to public key
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
$grant = new PasswordGrant(
new UserRepository(), // instance of UserRepositoryInterface

View File

@@ -32,6 +32,7 @@ $app = new App([
$refreshTokenRepository = new RefreshTokenRepository();
$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';
// Setup the authorization server
$server = new AuthorizationServer(
@@ -39,8 +40,9 @@ $app = new App([
$accessTokenRepository,
$scopeRepository,
$privateKeyPath,
'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
$publicKeyPath
);
$server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
// Enable the refresh token grant on the server
$grant = new RefreshTokenGrant($refreshTokenRepository);

View File

@@ -17,7 +17,7 @@ class ClientRepository implements ClientRepositoryInterface
/**
* {@inheritdoc}
*/
public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true)
public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
{
$clients = [
'myawesomeapp' => [

View File

@@ -1,10 +0,0 @@
includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
- vendor/phpstan/phpstan-phpunit/strictRules.neon
- vendor/phpstan/phpstan-strict-rules/rules.neon
services:
-
class: LeagueTests\PHPStan\AbstractGrantExtension
tags:
- phpstan.broker.dynamicMethodReturnTypeExtension

View File

@@ -9,7 +9,6 @@
namespace League\OAuth2\Server;
use Defuse\Crypto\Key;
use League\Event\EmitterAwareInterface;
use League\Event\EmitterAwareTrait;
use League\OAuth2\Server\Exception\OAuthServerException;
@@ -18,7 +17,6 @@ use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use League\OAuth2\Server\ResponseTypes\AbstractResponseType;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ResponseInterface;
@@ -28,6 +26,8 @@ class AuthorizationServer implements EmitterAwareInterface
{
use EmitterAwareTrait;
const ENCRYPTION_KEY_ERROR = 'You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/';
/**
* @var GrantTypeInterface[]
*/
@@ -68,15 +68,10 @@ class AuthorizationServer implements EmitterAwareInterface
*/
private $scopeRepository;
/**
* @var string|Key
*/
private $encryptionKey;
/**
* @var string
*/
private $defaultScope = '';
private $encryptionKey;
/**
* New server instance.
@@ -85,7 +80,7 @@ class AuthorizationServer implements EmitterAwareInterface
* @param AccessTokenRepositoryInterface $accessTokenRepository
* @param ScopeRepositoryInterface $scopeRepository
* @param CryptKey|string $privateKey
* @param string|Key $encryptionKey
* @param CryptKey|string $publicKey
* @param null|ResponseTypeInterface $responseType
*/
public function __construct(
@@ -93,7 +88,7 @@ class AuthorizationServer implements EmitterAwareInterface
AccessTokenRepositoryInterface $accessTokenRepository,
ScopeRepositoryInterface $scopeRepository,
$privateKey,
$encryptionKey,
$publicKey,
ResponseTypeInterface $responseType = null
) {
$this->clientRepository = $clientRepository;
@@ -104,10 +99,25 @@ class AuthorizationServer implements EmitterAwareInterface
$privateKey = new CryptKey($privateKey);
}
$this->privateKey = $privateKey;
$this->encryptionKey = $encryptionKey;
if ($publicKey instanceof CryptKey === false) {
$publicKey = new CryptKey($publicKey);
}
$this->publicKey = $publicKey;
$this->responseType = $responseType;
}
/**
* Set the encryption key
*
* @param string $key
*/
public function setEncryptionKey($key)
{
$this->encryptionKey = $key;
}
/**
* Enable a grant type on the server.
*
@@ -123,9 +133,15 @@ class AuthorizationServer implements EmitterAwareInterface
$grantType->setAccessTokenRepository($this->accessTokenRepository);
$grantType->setClientRepository($this->clientRepository);
$grantType->setScopeRepository($this->scopeRepository);
$grantType->setDefaultScope($this->defaultScope);
$grantType->setPrivateKey($this->privateKey);
$grantType->setPublicKey($this->publicKey);
$grantType->setEmitter($this->getEmitter());
if ($this->encryptionKey === null) {
// @codeCoverageIgnoreStart
trigger_error(self::ENCRYPTION_KEY_ERROR, E_USER_DEPRECATED);
// @codeCoverageIgnoreEnd
}
$grantType->setEncryptionKey($this->encryptionKey);
$this->enabledGrantTypes[$grantType->getIdentifier()] = $grantType;
@@ -143,6 +159,12 @@ class AuthorizationServer implements EmitterAwareInterface
*/
public function validateAuthorizationRequest(ServerRequestInterface $request)
{
if ($this->encryptionKey === null) {
// @codeCoverageIgnoreStart
trigger_error(self::ENCRYPTION_KEY_ERROR, E_USER_DEPRECATED);
// @codeCoverageIgnoreEnd
}
foreach ($this->enabledGrantTypes as $grantType) {
if ($grantType->canRespondToAuthorizationRequest($request)) {
return $grantType->validateAuthorizationRequest($request);
@@ -180,17 +202,16 @@ class AuthorizationServer implements EmitterAwareInterface
public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseInterface $response)
{
foreach ($this->enabledGrantTypes as $grantType) {
if (!$grantType->canRespondToAccessTokenRequest($request)) {
continue;
}
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($grantType->canRespondToAccessTokenRequest($request)) {
$tokenResponse = $grantType->respondToAccessTokenRequest(
$request,
$this->getResponseType(),
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()]
);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
if ($tokenResponse instanceof ResponseTypeInterface) {
return $tokenResponse->generateHttpResponse($response);
}
}
}
@@ -208,21 +229,9 @@ class AuthorizationServer implements EmitterAwareInterface
$this->responseType = new BearerTokenResponse();
}
if ($this->responseType instanceof AbstractResponseType === true) {
$this->responseType->setPrivateKey($this->privateKey);
}
$this->responseType->setPrivateKey($this->privateKey);
$this->responseType->setEncryptionKey($this->encryptionKey);
return $this->responseType;
}
/**
* Set the default scope for the authorization server.
*
* @param string $defaultScope
*/
public function setDefaultScope($defaultScope)
{
$this->defaultScope = $defaultScope;
}
}

View File

@@ -12,7 +12,6 @@ namespace League\OAuth2\Server\AuthorizationValidators;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\ValidationData;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\CryptTrait;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
@@ -27,11 +26,6 @@ class BearerTokenValidator implements AuthorizationValidatorInterface
*/
private $accessTokenRepository;
/**
* @var \League\OAuth2\Server\CryptKey
*/
protected $publicKey;
/**
* @param AccessTokenRepositoryInterface $accessTokenRepository
*/
@@ -40,16 +34,6 @@ class BearerTokenValidator implements AuthorizationValidatorInterface
$this->accessTokenRepository = $accessTokenRepository;
}
/**
* Set the public key
*
* @param \League\OAuth2\Server\CryptKey $key
*/
public function setPublicKey(CryptKey $key)
{
$this->publicKey = $key;
}
/**
* {@inheritdoc}
*/
@@ -65,12 +49,8 @@ class BearerTokenValidator implements AuthorizationValidatorInterface
try {
// Attempt to parse and validate the JWT
$token = (new Parser())->parse($jwt);
try {
if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
throw OAuthServerException::accessDenied('Access token could not be verified');
}
} catch (\BadMethodCallException $exception) {
throw OAuthServerException::accessDenied('Access token is not signed');
if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
throw OAuthServerException::accessDenied('Access token could not be verified');
}
// Ensure access token hasn't expired

View File

@@ -14,7 +14,7 @@ namespace League\OAuth2\Server;
class CryptKey
{
const RSA_KEY_PATTERN =
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----)\R.*(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)\R?$/s';
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/';
/**
* @var string
@@ -48,12 +48,14 @@ class CryptKey
if ($keyPermissionsCheck === true) {
// Verify the permissions of the key
$keyPathPerms = decoct(fileperms($keyPath) & 0777);
if (in_array($keyPathPerms, ['400', '440', '600', '640', '660'], true) === false) {
if (in_array($keyPathPerms, ['600', '660'], true) === false) {
// @codeCoverageIgnoreStart
trigger_error(sprintf(
'Key file "%s" permissions are not correct, recommend changing to 600 or 660 instead of %s',
'Key file "%s" permissions are not correct, should be 600 or 660 instead of %s',
$keyPath,
$keyPathPerms
), E_USER_NOTICE);
// @codeCoverageIgnoreEnd
}
}
@@ -73,25 +75,21 @@ class CryptKey
$tmpDir = sys_get_temp_dir();
$keyPath = $tmpDir . '/' . sha1($key) . '.key';
if (file_exists($keyPath)) {
return 'file://' . $keyPath;
}
if (!touch($keyPath)) {
if (!file_exists($keyPath) && !touch($keyPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('"%s" key file could not be created', $keyPath));
throw new \RuntimeException('"%s" key file could not be created', $keyPath);
// @codeCoverageIgnoreEnd
}
if (file_put_contents($keyPath, $key) === false) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('Unable to write key file to temporary directory "%s"', $tmpDir));
throw new \RuntimeException('Unable to write key file to temporary directory "%s"', $tmpDir);
// @codeCoverageIgnoreEnd
}
if (chmod($keyPath, 0600) === false) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf('The key file "%s" file mode could not be changed with chmod to 600', $keyPath));
throw new \RuntimeException('The key file "%s" file mode could not be changed with chmod to 600', $keyPath);
// @codeCoverageIgnoreEnd
}

View File

@@ -1,6 +1,6 @@
<?php
/**
* Encrypt/decrypt with encryptionKey.
* Public/private key encryption.
*
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
@@ -12,17 +12,46 @@
namespace League\OAuth2\Server;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
trait CryptTrait
{
/**
* @var string|Key
* @var CryptKey
*/
protected $privateKey;
/**
* @var CryptKey
*/
protected $publicKey;
/**
* @var string
*/
protected $encryptionKey;
/**
* Encrypt data with encryptionKey.
* Set path to private key.
*
* @param CryptKey $privateKey
*/
public function setPrivateKey(CryptKey $privateKey)
{
$this->privateKey = $privateKey;
}
/**
* Set path to public key.
*
* @param CryptKey $publicKey
*/
public function setPublicKey(CryptKey $publicKey)
{
$this->publicKey = $publicKey;
}
/**
* Encrypt data with a private key.
*
* @param string $unencryptedData
*
@@ -32,19 +61,38 @@ trait CryptTrait
*/
protected function encrypt($unencryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::encrypt($unencryptedData, $this->encryptionKey);
}
if ($this->encryptionKey !== null) {
return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey);
} catch (\Exception $e) {
throw new \LogicException($e->getMessage());
}
$privateKey = openssl_pkey_get_private($this->privateKey->getKeyPath(), $this->privateKey->getPassPhrase());
$privateKeyDetails = @openssl_pkey_get_details($privateKey);
if ($privateKeyDetails === null) {
throw new \LogicException(
sprintf('Could not get details of private key: %s', $this->privateKey->getKeyPath())
);
}
$chunkSize = ceil($privateKeyDetails['bits'] / 8) - 11;
$output = '';
while ($unencryptedData) {
$chunk = substr($unencryptedData, 0, $chunkSize);
$unencryptedData = substr($unencryptedData, $chunkSize);
if (openssl_private_encrypt($chunk, $encrypted, $privateKey) === false) {
// @codeCoverageIgnoreStart
throw new \LogicException('Failed to encrypt data');
// @codeCoverageIgnoreEnd
}
$output .= $encrypted;
}
openssl_pkey_free($privateKey);
return base64_encode($output);
}
/**
* Decrypt data with encryptionKey.
* Decrypt data with a public key.
*
* @param string $encryptedData
*
@@ -54,21 +102,42 @@ trait CryptTrait
*/
protected function decrypt($encryptedData)
{
try {
if ($this->encryptionKey instanceof Key) {
return Crypto::decrypt($encryptedData, $this->encryptionKey);
}
if ($this->encryptionKey !== null) {
return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey);
} catch (\Exception $e) {
throw new \LogicException($e->getMessage());
}
$publicKey = openssl_pkey_get_public($this->publicKey->getKeyPath());
$publicKeyDetails = @openssl_pkey_get_details($publicKey);
if ($publicKeyDetails === null) {
throw new \LogicException(
sprintf('Could not get details of public key: %s', $this->publicKey->getKeyPath())
);
}
$chunkSize = ceil($publicKeyDetails['bits'] / 8);
$output = '';
$encryptedData = base64_decode($encryptedData);
while ($encryptedData) {
$chunk = substr($encryptedData, 0, $chunkSize);
$encryptedData = substr($encryptedData, $chunkSize);
if (openssl_public_decrypt($chunk, $decrypted, $publicKey/*, OPENSSL_PKCS1_OAEP_PADDING*/) === false) {
// @codeCoverageIgnoreStart
throw new \LogicException('Failed to decrypt data');
// @codeCoverageIgnoreEnd
}
$output .= $decrypted;
}
openssl_pkey_free($publicKey);
return $output;
}
/**
* Set the encryption key
*
* @param string|Key $key
* @param string $key
*/
public function setEncryptionKey($key = null)
{

View File

@@ -9,7 +9,6 @@
namespace League\OAuth2\Server\Entities;
use Lcobucci\JWT\Token;
use League\OAuth2\Server\CryptKey;
interface AccessTokenEntityInterface extends TokenInterface
@@ -19,7 +18,7 @@ interface AccessTokenEntityInterface extends TokenInterface
*
* @param CryptKey $privateKey
*
* @return Token
* @return string
*/
public function convertToJWT(CryptKey $privateKey);
}

View File

@@ -12,7 +12,7 @@ namespace League\OAuth2\Server\Entities;
interface AuthCodeEntityInterface extends TokenInterface
{
/**
* @return string|null
* @return string
*/
public function getRedirectUri();

View File

@@ -21,7 +21,7 @@ interface RefreshTokenEntityInterface
/**
* Set the token's identifier.
*
* @param mixed $identifier
* @param $identifier
*/
public function setIdentifier($identifier);

View File

@@ -21,7 +21,7 @@ interface TokenInterface
/**
* Set the token's identifier.
*
* @param mixed $identifier
* @param $identifier
*/
public function setIdentifier($identifier);
@@ -42,14 +42,14 @@ interface TokenInterface
/**
* Set the identifier of the user associated with the token.
*
* @param string|int|null $identifier The identifier of the user
* @param string|int $identifier The identifier of the user
*/
public function setUserIdentifier($identifier);
/**
* Get the token user's identifier.
*
* @return string|int|null
* @return string|int
*/
public function getUserIdentifier();

View File

@@ -12,7 +12,6 @@ namespace League\OAuth2\Server\Entities\Traits;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
@@ -24,7 +23,7 @@ trait AccessTokenTrait
*
* @param CryptKey $privateKey
*
* @return Token
* @return string
*/
public function convertToJWT(CryptKey $privateKey)
{

View File

@@ -17,7 +17,7 @@ trait AuthCodeTrait
protected $redirectUri;
/**
* @return string|null
* @return string
*/
public function getRedirectUri()
{

View File

@@ -11,7 +11,7 @@ namespace League\OAuth2\Server\Entities\Traits;
trait EntityTrait
{
/**
/*
* @var string
*/
protected $identifier;

View File

@@ -25,7 +25,7 @@ trait TokenEntityTrait
protected $expiryDateTime;
/**
* @var string|int|null
* @var string|int
*/
protected $userIdentifier;
@@ -77,7 +77,7 @@ trait TokenEntityTrait
/**
* Set the identifier of the user associated with the token.
*
* @param string|int|null $identifier The identifier of the user
* @param string|int $identifier The identifier of the user
*/
public function setUserIdentifier($identifier)
{
@@ -87,7 +87,7 @@ trait TokenEntityTrait
/**
* Get the token user's identifier.
*
* @return string|int|null
* @return string|int
*/
public function getUserIdentifier()
{

View File

@@ -33,11 +33,6 @@ class OAuthServerException extends \Exception
*/
private $redirectUri;
/**
* @var array
*/
private $payload;
/**
* Throw a new exception.
*
@@ -55,33 +50,6 @@ class OAuthServerException extends \Exception
$this->errorType = $errorType;
$this->hint = $hint;
$this->redirectUri = $redirectUri;
$this->payload = [
'error' => $errorType,
'message' => $message,
];
if ($hint !== null) {
$this->payload['hint'] = $hint;
}
}
/**
* Returns the current payload.
*
* @return array
*/
public function getPayload()
{
return $this->payload;
}
/**
* Updates the current payload.
*
* @param array $payload
*/
public function setPayload(array $payload)
{
$this->payload = $payload;
}
/**
@@ -92,7 +60,7 @@ class OAuthServerException extends \Exception
public static function unsupportedGrantType()
{
$errorMessage = 'The authorization grant type is not supported by the authorization server.';
$hint = 'Check that all required parameters have been provided';
$hint = 'Check the `grant_type` parameter';
return new static($errorMessage, 2, 'unsupported_grant_type', 400, $hint);
}
@@ -137,15 +105,10 @@ class OAuthServerException extends \Exception
public static function invalidScope($scope, $redirectUri = null)
{
$errorMessage = 'The requested scope is invalid, unknown, or malformed';
if (empty($scope)) {
$hint = 'Specify a scope in the request or set a default scope';
} else {
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
}
$hint = sprintf(
'Check the `%s` scope',
htmlspecialchars($scope, ENT_QUOTES, 'UTF-8', false)
);
return new static($errorMessage, 5, 'invalid_scope', 400, $hint, $redirectUri);
}
@@ -163,7 +126,7 @@ class OAuthServerException extends \Exception
/**
* Server error.
*
* @param string $hint
* @param $hint
*
* @return static
*
@@ -189,7 +152,7 @@ class OAuthServerException extends \Exception
*/
public static function invalidRefreshToken($hint = null)
{
return new static('The refresh token is invalid.', 8, 'invalid_request', 401, $hint);
return new static('The refresh token is invalid.', 8, 'invalid_request', 400, $hint);
}
/**
@@ -245,15 +208,21 @@ class OAuthServerException extends \Exception
*
* @param ResponseInterface $response
* @param bool $useFragment True if errors should be in the URI fragment instead of query string
* @param int $jsonOptions options passed to json_encode
*
* @return ResponseInterface
*/
public function generateHttpResponse(ResponseInterface $response, $useFragment = false, $jsonOptions = 0)
public function generateHttpResponse(ResponseInterface $response, $useFragment = false)
{
$headers = $this->getHttpHeaders();
$payload = $this->getPayload();
$payload = [
'error' => $this->getErrorType(),
'message' => $this->getMessage(),
];
if ($this->hint !== null) {
$payload['hint'] = $this->hint;
}
if ($this->redirectUri !== null) {
if ($useFragment === true) {
@@ -269,7 +238,7 @@ class OAuthServerException extends \Exception
$response = $response->withHeader($header, $content);
}
$response->getBody()->write(json_encode($payload, $jsonOptions));
$response->getBody()->write(json_encode($payload));
return $response->withStatus($this->getHttpStatusCode());
}
@@ -294,30 +263,19 @@ class OAuthServerException extends \Exception
// include the "WWW-Authenticate" response header field
// matching the authentication scheme used by the client.
// @codeCoverageIgnoreStart
if ($this->errorType === 'invalid_client' && array_key_exists('HTTP_AUTHORIZATION', $_SERVER) !== false) {
$authScheme = strpos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer') === 0 ? 'Bearer' : 'Basic';
if ($this->errorType === 'invalid_client') {
$authScheme = 'Basic';
if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER) !== false
&& strpos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer') === 0
) {
$authScheme = 'Bearer';
}
$headers['WWW-Authenticate'] = $authScheme . ' realm="OAuth"';
}
// @codeCoverageIgnoreEnd
return $headers;
}
/**
* Check if the exception has an associated redirect URI.
*
* Returns whether the exception includes a redirect, since
* getHttpStatusCode() doesn't return a 302 when there's a
* redirect enabled. This helps when you want to override local
* error pages but want to let redirects through.
*
* @return bool
*/
public function hasRedirect()
{
return $this->redirectUri !== null;
}
/**
* Returns the HTTP status code to send when the exceptions is output.
*

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\Grant;
use League\Event\EmitterAwareTrait;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\CryptTrait;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
@@ -76,16 +75,6 @@ abstract class AbstractGrant implements GrantTypeInterface
*/
protected $refreshTokenTTL;
/**
* @var \League\OAuth2\Server\CryptKey
*/
protected $privateKey;
/**
* @string
*/
protected $defaultScope;
/**
* @param ClientRepositoryInterface $clientRepository
*/
@@ -142,24 +131,6 @@ abstract class AbstractGrant implements GrantTypeInterface
$this->refreshTokenTTL = $refreshTokenTTL;
}
/**
* Set the private key
*
* @param \League\OAuth2\Server\CryptKey $key
*/
public function setPrivateKey(CryptKey $key)
{
$this->privateKey = $key;
}
/**
* @param string $scope
*/
public function setDefaultScope($scope)
{
$this->defaultScope = $scope;
}
/**
* Validate the client.
*
@@ -193,43 +164,27 @@ abstract class AbstractGrant implements GrantTypeInterface
throw OAuthServerException::invalidClient();
}
// If a redirect URI is provided ensure it matches what is pre-registered
$redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
if ($redirectUri !== null) {
$this->validateRedirectUri($redirectUri, $client, $request);
if (
is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
}
return $client;
}
/**
* Validate redirectUri from the request.
* If a redirect URI is provided ensure it matches what is pre-registered
*
* @param string $redirectUri
* @param ClientEntityInterface $client
* @param ServerRequestInterface $request
*
* @throws OAuthServerException
*/
protected function validateRedirectUri(
string $redirectUri,
ClientEntityInterface $client,
ServerRequestInterface $request
) {
if (is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri(), true) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
}
/**
* Validate scopes in the request.
*
@@ -240,14 +195,18 @@ abstract class AbstractGrant implements GrantTypeInterface
*
* @return ScopeEntityInterface[]
*/
public function validateScopes($scopes, $redirectUri = null)
{
$scopesList = array_filter(explode(self::SCOPE_DELIMITER_STRING, trim($scopes)), function ($scope) {
return !empty($scope);
});
$validScopes = [];
public function validateScopes(
$scopes,
$redirectUri = null
) {
$scopesList = array_filter(
explode(self::SCOPE_DELIMITER_STRING, trim($scopes)),
function ($scope) {
return !empty($scope);
}
);
$scopes = [];
foreach ($scopesList as $scopeItem) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);
@@ -255,10 +214,10 @@ abstract class AbstractGrant implements GrantTypeInterface
throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
}
$validScopes[] = $scope;
$scopes[] = $scope;
}
return $validScopes;
return $scopes;
}
/**
@@ -357,7 +316,7 @@ abstract class AbstractGrant implements GrantTypeInterface
*
* @param \DateInterval $accessTokenTTL
* @param ClientEntityInterface $client
* @param string|null $userIdentifier
* @param string $userIdentifier
* @param ScopeEntityInterface[] $scopes
*
* @throws OAuthServerException
@@ -402,7 +361,7 @@ abstract class AbstractGrant implements GrantTypeInterface
* @param \DateInterval $authCodeTTL
* @param ClientEntityInterface $client
* @param string $userIdentifier
* @param string|null $redirectUri
* @param string $redirectUri
* @param ScopeEntityInterface[] $scopes
*
* @throws OAuthServerException
@@ -423,10 +382,7 @@ abstract class AbstractGrant implements GrantTypeInterface
$authCode->setExpiryDateTime((new \DateTime())->add($authCodeTTL));
$authCode->setClient($client);
$authCode->setUserIdentifier($userIdentifier);
if ($redirectUri !== null) {
$authCode->setRedirectUri($redirectUri);
}
$authCode->setRedirectUri($redirectUri);
foreach ($scopes as $scope) {
$authCode->addScope($scope);

View File

@@ -134,15 +134,6 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidRequest('code_verifier');
}
// Validate code_verifier according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.1
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeVerifier) !== 1) {
throw OAuthServerException::invalidRequest(
'code_verifier',
'Code Verifier must follow the specifications of RFC-7636.'
);
}
switch ($authCodePayload->code_challenge_method) {
case 'plain':
if (hash_equals($codeVerifier, $authCodePayload->code_challenge) === false) {
@@ -153,7 +144,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
case 'S256':
if (
hash_equals(
strtr(rtrim(base64_encode(hash('sha256', $codeVerifier, true)), '='), '+/', '-_'),
urlencode(base64_encode(hash('sha256', $codeVerifier))),
$authCodePayload->code_challenge
) === false
) {
@@ -176,10 +167,6 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $authCodePayload->user_id, $scopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response type
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
@@ -222,7 +209,6 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
$request,
$this->getServerParameter('PHP_AUTH_USER', $request)
);
if (is_null($clientId)) {
throw OAuthServerException::invalidRequest('client_id');
}
@@ -240,22 +226,27 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
}
$redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
if ($redirectUri !== null) {
$this->validateRedirectUri($redirectUri, $client, $request);
} elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
|| empty($client->getRedirectUri())) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} else {
$redirectUri = is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri();
if (
is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
$redirectUri
$this->getQueryStringParameter('scope', $request),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
);
$stateParameter = $this->getQueryStringParameter('state', $request);
@@ -264,11 +255,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
$authorizationRequest->setGrantTypeId($this->getIdentifier());
$authorizationRequest->setClient($client);
$authorizationRequest->setRedirectUri($redirectUri);
if ($stateParameter !== null) {
$authorizationRequest->setState($stateParameter);
}
$authorizationRequest->setState($stateParameter);
$authorizationRequest->setScopes($scopes);
if ($this->enableCodeExchangeProof === true) {
@@ -277,21 +264,18 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
throw OAuthServerException::invalidRequest('code_challenge');
}
$codeChallengeMethod = $this->getQueryStringParameter('code_challenge_method', $request, 'plain');
if (in_array($codeChallengeMethod, ['plain', 'S256'], true) === false) {
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
throw OAuthServerException::invalidRequest(
'code_challenge_method',
'Code challenge method must be `plain` or `S256`'
'code_challenge',
'The code_challenge must be between 43 and 128 characters'
);
}
// Validate code_challenge according to RFC-7636
// @see: https://tools.ietf.org/html/rfc7636#section-4.2
if (preg_match('/^[A-Za-z0-9-._~]{43,128}$/', $codeChallenge) !== 1) {
$codeChallengeMethod = $this->getQueryStringParameter('code_challenge_method', $request, 'plain');
if (in_array($codeChallengeMethod, ['plain', 'S256']) === false) {
throw OAuthServerException::invalidRequest(
'code_challenged',
'Code challenge must follow the specifications of RFC-7636.'
'code_challenge_method',
'Code challenge method must be `plain` or `S256`'
);
}
@@ -328,16 +312,30 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
);
$payload = [
'client_id' => $authCode->getClient()->getIdentifier(),
'redirect_uri' => $authCode->getRedirectUri(),
'auth_code_id' => $authCode->getIdentifier(),
'scopes' => $authCode->getScopes(),
'user_id' => $authCode->getUserIdentifier(),
'expire_time' => (new \DateTime())->add($this->authCodeTTL)->format('U'),
'code_challenge' => $authorizationRequest->getCodeChallenge(),
'code_challenge_method' => $authorizationRequest->getCodeChallengeMethod(),
'client_id' => $authCode->getClient()->getIdentifier(),
'redirect_uri' => $authCode->getRedirectUri(),
'auth_code_id' => $authCode->getIdentifier(),
'scopes' => $authCode->getScopes(),
'user_id' => $authCode->getUserIdentifier(),
'expire_time' => (new \DateTime())->add($this->authCodeTTL)->format('U'),
'code_challenge' => $authorizationRequest->getCodeChallenge(),
'code_challenge_method ' => $authorizationRequest->getCodeChallengeMethod(),
];
if ($this->encryptionKey === null) {
// Add padding to vary the length of the payload
$payload['_padding'] = base64_encode(random_bytes(mt_rand(8, 256)));
// Shuffle the payload so that the structure is no longer know and obvious
$keys = array_keys($payload);
shuffle($keys);
$shuffledPayload = [];
foreach ($keys as $key) {
$shuffledPayload[$key] = $payload[$key];
}
} else {
$shuffledPayload = $payload;
}
$response = new RedirectResponse();
$response->setRedirectUri(
$this->makeRedirectUri(
@@ -345,7 +343,7 @@ class AuthCodeGrant extends AbstractAuthorizeGrant
[
'code' => $this->encrypt(
json_encode(
$payload
$shuffledPayload
)
),
'state' => $authorizationRequest->getState(),

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\RequestEvent;
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
use Psr\Http\Message\ServerRequestInterface;
@@ -30,16 +29,13 @@ class ClientCredentialsGrant extends AbstractGrant
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
$scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
// Issue and persist access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $finalizedScopes);
// Send event to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $scopes);
// Inject access token into response type
$responseType->setAccessToken($accessToken);

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\Grant;
use Defuse\Crypto\Key;
use League\Event\EmitterAwareInterface;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
@@ -120,13 +119,6 @@ interface GrantTypeInterface extends EmitterAwareInterface
*/
public function setScopeRepository(ScopeRepositoryInterface $scopeRepository);
/**
* Set the default scope.
*
* @param string $scope
*/
public function setDefaultScope($scope);
/**
* Set the path to the private key.
*
@@ -134,10 +126,17 @@ interface GrantTypeInterface extends EmitterAwareInterface
*/
public function setPrivateKey(CryptKey $privateKey);
/**
* Set the path to the public key.
*
* @param CryptKey $publicKey
*/
public function setPublicKey(CryptKey $publicKey);
/**
* Set the encryption key
*
* @param string|Key|null $key
* @param string|null $key
*/
public function setEncryptionKey($key = null);
}

View File

@@ -26,19 +26,12 @@ class ImplicitGrant extends AbstractAuthorizeGrant
*/
private $accessTokenTTL;
/**
* @var string
*/
private $queryDelimiter;
/**
* @param \DateInterval $accessTokenTTL
* @param string $queryDelimiter
*/
public function __construct(\DateInterval $accessTokenTTL, $queryDelimiter = '#')
public function __construct(\DateInterval $accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
$this->queryDelimiter = $queryDelimiter;
}
/**
@@ -102,7 +95,7 @@ class ImplicitGrant extends AbstractAuthorizeGrant
public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
{
return (
isset($request->getQueryParams()['response_type'])
array_key_exists('response_type', $request->getQueryParams())
&& $request->getQueryParams()['response_type'] === 'token'
&& isset($request->getQueryParams()['client_id'])
);
@@ -118,7 +111,6 @@ class ImplicitGrant extends AbstractAuthorizeGrant
$request,
$this->getServerParameter('PHP_AUTH_USER', $request)
);
if (is_null($clientId)) {
throw OAuthServerException::invalidRequest('client_id');
}
@@ -136,26 +128,31 @@ class ImplicitGrant extends AbstractAuthorizeGrant
}
$redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
if ($redirectUri !== null) {
$this->validateRedirectUri($redirectUri, $client, $request);
} elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
|| empty($client->getRedirectUri())) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} else {
$redirectUri = is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri();
if (
is_string($client->getRedirectUri())
&& (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
} elseif (
is_array($client->getRedirectUri())
&& in_array($redirectUri, $client->getRedirectUri()) === false
) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
}
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
$redirectUri
$this->getQueryStringParameter('scope', $request),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
);
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes(
$scopes = $this->scopeRepository->finalizeScopes(
$scopes,
$this->getIdentifier(),
$client
@@ -167,12 +164,8 @@ class ImplicitGrant extends AbstractAuthorizeGrant
$authorizationRequest->setGrantTypeId($this->getIdentifier());
$authorizationRequest->setClient($client);
$authorizationRequest->setRedirectUri($redirectUri);
if ($stateParameter !== null) {
$authorizationRequest->setState($stateParameter);
}
$authorizationRequest->setScopes($finalizedScopes);
$authorizationRequest->setState($stateParameter);
$authorizationRequest->setScopes($scopes);
return $authorizationRequest;
}
@@ -207,11 +200,11 @@ class ImplicitGrant extends AbstractAuthorizeGrant
$finalRedirectUri,
[
'access_token' => (string) $accessToken->convertToJWT($this->privateKey),
'token_type' => 'Bearer',
'token_type' => 'bearer',
'expires_in' => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
'state' => $authorizationRequest->getState(),
],
$this->queryDelimiter
'#'
)
);

View File

@@ -49,20 +49,16 @@ class PasswordGrant extends AbstractGrant
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
$user = $this->validateUser($request, $client);
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
$scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
// Issue and persist new tokens
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $scopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);

View File

@@ -11,6 +11,7 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\RequestEvent;
@@ -43,17 +44,28 @@ class RefreshTokenGrant extends AbstractGrant
// Validate request
$client = $this->validateClient($request);
$oldRefreshToken = $this->validateOldRefreshToken($request, $client->getIdentifier());
$scopes = $this->validateScopes($this->getRequestParameter(
'scope',
$request,
implode(self::SCOPE_DELIMITER_STRING, $oldRefreshToken['scopes']))
);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
// The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
// the request doesn't include any new scopes
foreach ($scopes as $scope) {
if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes'], true) === false) {
throw OAuthServerException::invalidScope($scope->getIdentifier());
// If no new scopes are requested then give the access token the original session scopes
if (count($scopes) === 0) {
$scopes = array_map(function ($scopeId) use ($client) {
$scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeId);
if ($scope instanceof ScopeEntityInterface === false) {
// @codeCoverageIgnoreStart
throw OAuthServerException::invalidScope($scopeId);
// @codeCoverageIgnoreEnd
}
return $scope;
}, $oldRefreshToken['scopes']);
} else {
// The OAuth spec says that a refreshed access token can have the original scopes or fewer so ensure
// the request doesn't include any new scopes
foreach ($scopes as $scope) {
if (in_array($scope->getIdentifier(), $oldRefreshToken['scopes']) === false) {
throw OAuthServerException::invalidScope($scope->getIdentifier());
}
}
}
@@ -65,10 +77,6 @@ class RefreshTokenGrant extends AbstractGrant
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $oldRefreshToken['user_id'], $scopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Send events to emitter
$this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
$this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);

View File

@@ -12,7 +12,6 @@ namespace League\OAuth2\Server\Repositories;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
/**
* Access token interface.
@@ -34,8 +33,6 @@ interface AccessTokenRepositoryInterface extends RepositoryInterface
* Persists a new access token to permanent storage.
*
* @param AccessTokenEntityInterface $accessTokenEntity
*
* @throws UniqueTokenIdentifierConstraintViolationException
*/
public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity);

View File

@@ -10,7 +10,6 @@
namespace League\OAuth2\Server\Repositories;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
/**
* Auth code storage interface.
@@ -28,8 +27,6 @@ interface AuthCodeRepositoryInterface extends RepositoryInterface
* Persists a new auth code to permanent storage.
*
* @param AuthCodeEntityInterface $authCodeEntity
*
* @throws UniqueTokenIdentifierConstraintViolationException
*/
public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity);

View File

@@ -20,12 +20,12 @@ interface ClientRepositoryInterface extends RepositoryInterface
* Get a client.
*
* @param string $clientIdentifier The client's identifier
* @param null|string $grantType The grant type used (if sent)
* @param string $grantType The grant type used
* @param null|string $clientSecret The client's secret (if sent)
* @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client
* is confidential
*
* @return ClientEntityInterface
*/
public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true);
public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true);
}

View File

@@ -10,7 +10,6 @@
namespace League\OAuth2\Server\Repositories;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
/**
* Refresh token interface.
@@ -28,8 +27,6 @@ interface RefreshTokenRepositoryInterface extends RepositoryInterface
* Create a new refresh token_name.
*
* @param RefreshTokenEntityInterface $refreshTokenEntity
*
* @throws UniqueTokenIdentifierConstraintViolationException
*/
public function persistNewRefreshToken(RefreshTokenEntityInterface $refreshTokenEntity);

View File

@@ -18,9 +18,6 @@ class RequestEvent extends Event
const USER_AUTHENTICATION_FAILED = 'user.authentication.failed';
const REFRESH_TOKEN_CLIENT_FAILED = 'refresh_token.client.failed';
const REFRESH_TOKEN_ISSUED = 'refresh_token.issued';
const ACCESS_TOKEN_ISSUED = 'access_token.issued';
/**
* @var ServerRequestInterface
*/

View File

@@ -53,14 +53,14 @@ class AuthorizationRequest
/**
* The redirect URI used in the request
*
* @var string|null
* @var string
*/
protected $redirectUri;
/**
* The state parameter on the authorization request
*
* @var string|null
* @var string
*/
protected $state;
@@ -159,7 +159,7 @@ class AuthorizationRequest
}
/**
* @return string|null
* @return string
*/
public function getRedirectUri()
{
@@ -167,7 +167,7 @@ class AuthorizationRequest
}
/**
* @param string|null $redirectUri
* @param string $redirectUri
*/
public function setRedirectUri($redirectUri)
{
@@ -175,7 +175,7 @@ class AuthorizationRequest
}
/**
* @return string|null
* @return string
*/
public function getState()
{

View File

@@ -63,9 +63,7 @@ class ResourceServer
$this->authorizationValidator = new BearerTokenValidator($this->accessTokenRepository);
}
if ($this->authorizationValidator instanceof BearerTokenValidator === true) {
$this->authorizationValidator->setPublicKey($this->publicKey);
}
$this->authorizationValidator->setPublicKey($this->publicKey);
return $this->authorizationValidator;
}

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\ResponseTypes;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\CryptTrait;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
@@ -30,11 +29,6 @@ abstract class AbstractResponseType implements ResponseTypeInterface
*/
protected $refreshToken;
/**
* @var CryptKey
*/
protected $privateKey;
/**
* {@inheritdoc}
*/
@@ -50,14 +44,4 @@ abstract class AbstractResponseType implements ResponseTypeInterface
{
$this->refreshToken = $refreshToken;
}
/**
* Set the private key
*
* @param \League\OAuth2\Server\CryptKey $key
*/
public function setPrivateKey(CryptKey $key)
{
$this->privateKey = $key;
}
}

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\ResponseTypes;
use Defuse\Crypto\Key;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use Psr\Http\Message\ResponseInterface;
@@ -38,7 +37,7 @@ interface ResponseTypeInterface
/**
* Set the encryption key
*
* @param string|Key|null $key
* @param string|null $key
*/
public function setEncryptionKey($key = null);
}

View File

@@ -3,6 +3,7 @@
namespace LeagueTests;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\AuthCodeGrant;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
@@ -16,27 +17,15 @@ use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\AuthCodeEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\ServerRequestFactory;
class AuthorizationServerTest extends TestCase
class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
public function setUp()
{
// Make sure the keys have the correct permissions.
chmod(__DIR__ . '/Stubs/private.key', 0600);
chmod(__DIR__ . '/Stubs/public.key', 0600);
chmod(__DIR__ . '/Stubs/private.key.crlf', 0600);
}
public function testRespondToRequestInvalidGrantType()
{
$server = new AuthorizationServer(
@@ -44,9 +33,10 @@ class AuthorizationServerTest extends TestCase
$this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(),
$this->getMockBuilder(ScopeRepositoryInterface::class)->getMock(),
'file://' . __DIR__ . '/Stubs/private.key',
base64_encode(random_bytes(36)),
'file://' . __DIR__ . '/Stubs/public.key',
new StubResponseType()
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M'));
@@ -63,9 +53,7 @@ class AuthorizationServerTest extends TestCase
$clientRepository = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepository->method('getClientEntity')->willReturn(new ClientEntity());
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
@@ -76,11 +64,11 @@ class AuthorizationServerTest extends TestCase
$accessTokenRepositoryMock,
$scopeRepositoryMock,
'file://' . __DIR__ . '/Stubs/private.key',
base64_encode(random_bytes(36)),
'file://' . __DIR__ . '/Stubs/public.key',
new StubResponseType()
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$server->setDefaultScope(self::DEFAULT_SCOPE);
$server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M'));
$_POST['grant_type'] = 'client_credentials';
@@ -101,12 +89,13 @@ class AuthorizationServerTest extends TestCase
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$abstractGrantReflection = new \ReflectionClass($server);
$method = $abstractGrantReflection->getMethod('getResponseType');
$method->setAccessible(true);
$this->assertInstanceOf(BearerTokenResponse::class, $method->invoke($server));
$this->assertTrue($method->invoke($server) instanceof BearerTokenResponse);
}
public function testCompleteAuthorizationRequest()
@@ -120,6 +109,7 @@ class AuthorizationServerTest extends TestCase
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$authCodeRepository = $this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock();
$authCodeRepository->method('getNewAuthCode')->willReturn(new AuthCodeEntity());
@@ -130,6 +120,9 @@ class AuthorizationServerTest extends TestCase
new \DateInterval('PT10M')
);
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/Stubs/public.key'));
$server->enableGrantType($grant);
$authRequest = new AuthorizationRequest();
@@ -138,59 +131,12 @@ class AuthorizationServerTest extends TestCase
$authRequest->setGrantTypeId('authorization_code');
$authRequest->setUser(new UserEntity());
$this->assertInstanceOf(
ResponseInterface::class,
$server->completeAuthorizationRequest($authRequest, new Response)
$this->assertTrue(
$server->completeAuthorizationRequest($authRequest, new Response) instanceof ResponseInterface
);
}
public function testValidateAuthorizationRequest()
{
$client = new ClientEntity();
$client->setRedirectUri('http://foo/bar');
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);
$server = new AuthorizationServer(
$clientRepositoryMock,
$this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(),
$scopeRepositoryMock,
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->setDefaultScope(self::DEFAULT_SCOPE);
$server->enableGrantType($grant);
$request = new ServerRequest(
[],
[],
null,
null,
'php://input',
$headers = [],
$cookies = [],
$queryParams = [
'response_type' => 'code',
'client_id' => 'foo',
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $server->validateAuthorizationRequest($request));
}
public function testValidateAuthorizationRequestWithMissingRedirectUri()
{
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
@@ -210,6 +156,7 @@ class AuthorizationServerTest extends TestCase
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$server->enableGrantType($grant);
$request = new ServerRequest(
@@ -226,12 +173,7 @@ class AuthorizationServerTest extends TestCase
]
);
try {
$server->validateAuthorizationRequest($request);
} catch (OAuthServerException $e) {
$this->assertEquals('invalid_client', $e->getErrorType());
$this->assertEquals(401, $e->getHttpStatusCode());
}
$this->assertTrue($server->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
/**
@@ -247,6 +189,7 @@ class AuthorizationServerTest extends TestCase
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$request = new ServerRequest(
[],

View File

@@ -1,40 +0,0 @@
<?php
namespace LeagueTests\AuthorizationValidators;
use Lcobucci\JWT\Builder;
use League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class BearerTokenValidatorTest extends TestCase
{
/**
* @expectedException League\OAuth2\Server\Exception\OAuthServerException
* @expectedExceptionCode 9
*/
public function testThrowExceptionWhenAccessTokenIsNotSigned()
{
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$bearerTokenValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$bearerTokenValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$unsignedJwt = (new Builder())
->setAudience('client-id')
->setId('token-id', true)
->setIssuedAt(time())
->setNotBefore(time())
->setExpiration(time())
->setSubject('user-id')
->set('scopes', 'scope1 scope2 scope3 scope4')
->getToken();
$request = new ServerRequest();
$request = $request->withHeader('authorization', sprintf('Bearer %s', $unsignedJwt));
$bearerTokenValidator->validateAuthorization($request);
}
}

View File

@@ -3,9 +3,8 @@
namespace LeagueTests\Utils;
use League\OAuth2\Server\CryptKey;
use PHPUnit\Framework\TestCase;
class CryptKeyTest extends TestCase
class CryptKeyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \LogicException
@@ -17,7 +16,7 @@ class CryptKeyTest extends TestCase
public function testKeyCreation()
{
$keyFile = __DIR__ . '/../Stubs/public.key';
$keyFile = __DIR__ . '/Stubs/public.key';
$key = new CryptKey($keyFile, 'secret');
$this->assertEquals('file://' . $keyFile, $key->getKeyPath());
@@ -26,15 +25,7 @@ class CryptKeyTest extends TestCase
public function testKeyFileCreation()
{
$keyContent = file_get_contents(__DIR__ . '/../Stubs/public.key');
$key = new CryptKey($keyContent);
$this->assertEquals(
'file://' . sys_get_temp_dir() . '/' . sha1($keyContent) . '.key',
$key->getKeyPath()
);
$keyContent = file_get_contents(__DIR__ . '/../Stubs/private.key.crlf');
$keyContent = file_get_contents(__DIR__ . '/Stubs/public.key');
$key = new CryptKey($keyContent);
$this->assertEquals(

55
tests/CryptTraitTest.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
namespace LeagueTests\Utils;
use League\OAuth2\Server\CryptKey;
use LeagueTests\Stubs\CryptTraitStub;
class CryptTraitTest extends \PHPUnit_Framework_TestCase
{
/**
* CryptTrait stub
*/
protected $cryptStub;
public function setUp()
{
$this->cryptStub = new CryptTraitStub;
}
public function testEncryptDecrypt()
{
$payload = 'alex loves whisky';
$encrypted = $this->cryptStub->doEncrypt($payload);
$plainText = $this->cryptStub->doDecrypt($encrypted);
$this->assertNotEquals($payload, $encrypted);
$this->assertEquals($payload, $plainText);
}
/**
* @expectedException \LogicException
*/
public function testBadPrivateKey()
{
$this->cryptStub->setPrivateKey(new CryptKey(__DIR__ . '/Stubs/public.key'));
$this->cryptStub->doEncrypt('');
}
/**
* @expectedException \LogicException
*/
public function testBadPublicKey()
{
$this->cryptStub->setPublicKey(new CryptKey(__DIR__ . '/Stubs/private.key'));
$this->cryptStub->doDecrypt('');
}
/**
* @expectedException \LogicException
*/
public function testNonExistentKey()
{
new CryptKey('foo/bar');
}
}

View File

@@ -1,23 +0,0 @@
<?php
namespace LeagueTests\Exception;
use League\OAuth2\Server\Exception\OAuthServerException;
use PHPUnit\Framework\TestCase;
class OAuthServerExceptionTest extends TestCase
{
public function testHasRedirect()
{
$exceptionWithRedirect = OAuthServerException::accessDenied('some hint', 'https://example.com/error');
$this->assertTrue($exceptionWithRedirect->hasRedirect());
}
public function testDoesNotHaveRedirect()
{
$exceptionWithoutRedirect = OAuthServerException::accessDenied('Some hint');
$this->assertFalse($exceptionWithoutRedirect->hasRedirect());
}
}

View File

@@ -3,6 +3,7 @@
namespace LeagueTests\Grant;
use League\Event\Emitter;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
@@ -18,15 +19,16 @@ use LeagueTests\Stubs\AuthCodeEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\RefreshTokenEntity;
use LeagueTests\Stubs\ScopeEntity;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class AbstractGrantTest extends TestCase
class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{
public function testGetSet()
{
/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setPrivateKey(new CryptKey(__DIR__ . '/../Stubs/private.key'));
$grantMock->setPublicKey(new CryptKey(__DIR__ . '/../Stubs/public.key'));
$grantMock->setEmitter(new Emitter());
}
@@ -342,7 +344,7 @@ class AbstractGrantTest extends TestCase
$accessToken = new AccessTokenEntity();
/** @var RefreshTokenEntityInterface $refreshToken */
$refreshToken = $issueRefreshTokenMethod->invoke($grantMock, $accessToken);
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $refreshToken);
$this->assertTrue($refreshToken instanceof RefreshTokenEntityInterface);
$this->assertEquals($accessToken, $refreshToken->getAccessToken());
}
@@ -367,7 +369,7 @@ class AbstractGrantTest extends TestCase
123,
[new ScopeEntity()]
);
$this->assertInstanceOf(AccessTokenEntityInterface::class, $accessToken);
$this->assertTrue($accessToken instanceof AccessTokenEntityInterface);
}
public function testIssueAuthCode()
@@ -383,8 +385,7 @@ class AbstractGrantTest extends TestCase
$issueAuthCodeMethod = $abstractGrantReflection->getMethod('issueAuthCode');
$issueAuthCodeMethod->setAccessible(true);
$this->assertInstanceOf(
AuthCodeEntityInterface::class,
$this->assertTrue(
$issueAuthCodeMethod->invoke(
$grantMock,
new \DateInterval('PT1H'),
@@ -392,7 +393,7 @@ class AbstractGrantTest extends TestCase
123,
'http://foo/bar',
[new ScopeEntity()]
)
) instanceof AuthCodeEntityInterface
);
}
@@ -468,7 +469,7 @@ class AbstractGrantTest extends TestCase
$method = $abstractGrantReflection->getMethod('generateUniqueIdentifier');
$method->setAccessible(true);
$this->assertInternalType('string', $method->invoke($grantMock));
$this->assertTrue(is_string($method->invoke($grantMock)));
}
public function testCanRespondToAuthorizationRequest()

View File

@@ -2,6 +2,7 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
@@ -22,22 +23,15 @@ use LeagueTests\Stubs\RefreshTokenEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class AuthCodeGrantTest extends TestCase
class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
/**
* @var CryptTraitStub
*/
protected $cryptStub;
const CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
const CODE_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
public function setUp()
{
$this->cryptStub = new CryptTraitStub;
@@ -83,22 +77,15 @@ class AuthCodeGrantTest extends TestCase
{
$client = new ClientEntity();
$client->setRedirectUri('http://foo/bar');
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -115,7 +102,7 @@ class AuthCodeGrantTest extends TestCase
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $grant->validateAuthorizationRequest($request));
$this->assertTrue($grant->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
public function testValidateAuthorizationRequestRedirectUriArray()
@@ -125,18 +112,12 @@ class AuthCodeGrantTest extends TestCase
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -153,7 +134,7 @@ class AuthCodeGrantTest extends TestCase
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $grant->validateAuthorizationRequest($request));
$this->assertTrue($grant->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
public function testValidateAuthorizationRequestCodeChallenge()
@@ -163,10 +144,6 @@ class AuthCodeGrantTest extends TestCase
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
@@ -174,8 +151,6 @@ class AuthCodeGrantTest extends TestCase
);
$grant->enableCodeExchangeProof();
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -189,11 +164,11 @@ class AuthCodeGrantTest extends TestCase
'response_type' => 'code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_challenge' => self::CODE_CHALLENGE,
'code_challenge' => str_repeat('A', 43),
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $grant->validateAuthorizationRequest($request));
$this->assertTrue($grant->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
/**
@@ -454,10 +429,6 @@ class AuthCodeGrantTest extends TestCase
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
@@ -465,8 +436,6 @@ class AuthCodeGrantTest extends TestCase
);
$grant->enableCodeExchangeProof();
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -497,10 +466,6 @@ class AuthCodeGrantTest extends TestCase
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
@@ -508,8 +473,6 @@ class AuthCodeGrantTest extends TestCase
);
$grant->enableCodeExchangeProof();
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -547,9 +510,11 @@ class AuthCodeGrantTest extends TestCase
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setEncryptionKey($this->cryptStub->getKey());
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
/**
@@ -572,7 +537,9 @@ class AuthCodeGrantTest extends TestCase
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->completeAuthorizationRequest($authRequest);
}
@@ -607,7 +574,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -640,8 +608,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
public function testRespondToAccessTokenRequestCodeChallengePlain()
@@ -675,7 +643,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -690,7 +659,7 @@ class AuthCodeGrantTest extends TestCase
'grant_type' => 'authorization_code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_verifier' => self::CODE_VERIFIER,
'code_verifier' => 'foobar',
'code' => $this->cryptStub->doEncrypt(
json_encode(
[
@@ -700,7 +669,7 @@ class AuthCodeGrantTest extends TestCase
'user_id' => 123,
'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar',
'code_challenge' => self::CODE_VERIFIER,
'code_challenge' => 'foobar',
'code_challenge_method' => 'plain',
]
)
@@ -711,8 +680,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
public function testRespondToAccessTokenRequestCodeChallengeS256()
@@ -746,7 +715,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -761,7 +731,7 @@ class AuthCodeGrantTest extends TestCase
'grant_type' => 'authorization_code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_verifier' => self::CODE_VERIFIER,
'code_verifier' => 'foobar',
'code' => $this->cryptStub->doEncrypt(
json_encode(
[
@@ -771,7 +741,7 @@ class AuthCodeGrantTest extends TestCase
'user_id' => 123,
'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar',
'code_challenge' => self::CODE_CHALLENGE,
'code_challenge' => urlencode(base64_encode(hash('sha256', 'foobar'))),
'code_challenge_method' => 'S256',
]
)
@@ -782,8 +752,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**
@@ -803,7 +773,7 @@ class AuthCodeGrantTest extends TestCase
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest(
[],
@@ -850,7 +820,7 @@ class AuthCodeGrantTest extends TestCase
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest(
[],
@@ -903,7 +873,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -948,7 +919,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1011,7 +983,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1071,7 +1044,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1131,7 +1105,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1189,7 +1164,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1204,7 +1180,7 @@ class AuthCodeGrantTest extends TestCase
'grant_type' => 'authorization_code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_verifier' => self::CODE_VERIFIER,
'code_verifier' => 'nope',
'code' => $this->cryptStub->doEncrypt(
json_encode(
[
@@ -1261,7 +1237,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1298,151 +1275,7 @@ class AuthCodeGrantTest extends TestCase
/* @var StubResponseType $response */
$grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
} catch (OAuthServerException $e) {
$this->assertEquals($e->getHint(), 'Code Verifier must follow the specifications of RFC-7636.');
}
}
public function testRespondToAccessTokenRequestMalformedCodeVerifierS256WithInvalidChars()
{
$client = new ClientEntity();
$client->setIdentifier('foo');
$client->setRedirectUri('http://foo/bar');
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeEntity = new ScopeEntity();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scopeEntity);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('getNewToken')->willReturn(new AccessTokenEntity());
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$refreshTokenRepositoryMock = $this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock();
$refreshTokenRepositoryMock->method('persistNewRefreshToken')->willReturnSelf();
$refreshTokenRepositoryMock->method('getNewRefreshToken')->willReturn(new RefreshTokenEntity());
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->enableCodeExchangeProof();
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$request = new ServerRequest(
[],
[],
null,
'POST',
'php://input',
[],
[],
[],
[
'grant_type' => 'authorization_code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_verifier' => 'dqX7C-RbqjHYtytmhGTigKdZCXfxq-+xbsk9_GxUcaE', // Malformed code. Contains `+`.
'code' => $this->cryptStub->doEncrypt(
json_encode(
[
'auth_code_id' => uniqid(),
'expire_time' => time() + 3600,
'client_id' => 'foo',
'user_id' => 123,
'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar',
'code_challenge' => self::CODE_CHALLENGE,
'code_challenge_method' => 'S256',
]
)
),
]
);
try {
/* @var StubResponseType $response */
$grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
} catch (OAuthServerException $e) {
$this->assertEquals($e->getHint(), 'Code Verifier must follow the specifications of RFC-7636.');
}
}
public function testRespondToAccessTokenRequestMalformedCodeVerifierS256WithInvalidLength()
{
$client = new ClientEntity();
$client->setIdentifier('foo');
$client->setRedirectUri('http://foo/bar');
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeEntity = new ScopeEntity();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scopeEntity);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('getNewToken')->willReturn(new AccessTokenEntity());
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$refreshTokenRepositoryMock = $this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock();
$refreshTokenRepositoryMock->method('persistNewRefreshToken')->willReturnSelf();
$refreshTokenRepositoryMock->method('getNewRefreshToken')->willReturn(new RefreshTokenEntity());
$grant = new AuthCodeGrant(
$this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock(),
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->enableCodeExchangeProof();
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$request = new ServerRequest(
[],
[],
null,
'POST',
'php://input',
[],
[],
[],
[
'grant_type' => 'authorization_code',
'client_id' => 'foo',
'redirect_uri' => 'http://foo/bar',
'code_verifier' => 'dqX7C-RbqjHY', // Malformed code. Invalid length.
'code' => $this->cryptStub->doEncrypt(
json_encode(
[
'auth_code_id' => uniqid(),
'expire_time' => time() + 3600,
'client_id' => 'foo',
'user_id' => 123,
'scopes' => ['foo'],
'redirect_uri' => 'http://foo/bar',
'code_challenge' => 'R7T1y1HPNFvs1WDCrx4lfoBS6KD2c71pr8OHvULjvv8',
'code_challenge_method' => 'S256',
]
)
),
]
);
try {
/* @var StubResponseType $response */
$grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
} catch (OAuthServerException $e) {
$this->assertEquals($e->getHint(), 'Code Verifier must follow the specifications of RFC-7636.');
$this->assertEquals($e->getHint(), 'Failed to verify `code_verifier`.');
}
}
@@ -1477,7 +1310,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1536,9 +1370,11 @@ class AuthCodeGrantTest extends TestCase
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setEncryptionKey($this->cryptStub->getKey());
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
/**
@@ -1562,9 +1398,11 @@ class AuthCodeGrantTest extends TestCase
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new \DateInterval('PT10M')
);
$grant->setEncryptionKey($this->cryptStub->getKey());
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
/**
@@ -1589,7 +1427,10 @@ class AuthCodeGrantTest extends TestCase
new \DateInterval('PT10M')
);
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
public function testRefreshTokenRepositoryUniqueConstraintCheck()
@@ -1623,7 +1464,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1656,8 +1498,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**
@@ -1694,7 +1536,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1727,8 +1570,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**
@@ -1765,7 +1608,8 @@ class AuthCodeGrantTest extends TestCase
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setRefreshTokenRepository($refreshTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$request = new ServerRequest(
[],
@@ -1798,8 +1642,8 @@ class AuthCodeGrantTest extends TestCase
/** @var StubResponseType $response */
$response = $grant->respondToAccessTokenRequest($request, new StubResponseType(), new \DateInterval('PT10M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $response->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $response->getRefreshToken());
$this->assertTrue($response->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($response->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**

View File

@@ -9,15 +9,11 @@ use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class ClientCredentialsGrantTest extends TestCase
class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
public function testGetIdentifier()
{
$grant = new ClientCredentialsGrant();
@@ -34,16 +30,13 @@ class ClientCredentialsGrantTest extends TestCase
$accessTokenRepositoryMock->method('getNewToken')->willReturn(new AccessTokenEntity());
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$grant = new ClientCredentialsGrant();
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody(
@@ -56,6 +49,6 @@ class ClientCredentialsGrantTest extends TestCase
$responseType = new StubResponseType();
$grant->respondToAccessTokenRequest($serverRequest, $responseType, new \DateInterval('PT5M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $responseType->getAccessToken());
$this->assertTrue($responseType->getAccessToken() instanceof AccessTokenEntityInterface);
}
}

View File

@@ -18,13 +18,10 @@ use LeagueTests\Stubs\CryptTraitStub;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class ImplicitGrantTest extends TestCase
class ImplicitGrantTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
/**
* CryptTrait stub
*/
@@ -99,7 +96,6 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -116,7 +112,7 @@ class ImplicitGrantTest extends TestCase
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $grant->validateAuthorizationRequest($request));
$this->assertTrue($grant->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
public function testValidateAuthorizationRequestRedirectUriArray()
@@ -134,7 +130,6 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$request = new ServerRequest(
[],
@@ -151,7 +146,7 @@ class ImplicitGrantTest extends TestCase
]
);
$this->assertInstanceOf(AuthorizationRequest::class, $grant->validateAuthorizationRequest($request));
$this->assertTrue($grant->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}
/**
@@ -288,9 +283,10 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
/**
@@ -311,6 +307,7 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->completeAuthorizationRequest($authRequest);
@@ -332,9 +329,10 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$this->assertInstanceOf(RedirectResponse::class, $grant->completeAuthorizationRequest($authRequest));
$this->assertTrue($grant->completeAuthorizationRequest($authRequest) instanceof RedirectResponse);
}
/**
@@ -356,6 +354,7 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->completeAuthorizationRequest($authRequest);
@@ -380,6 +379,7 @@ class ImplicitGrantTest extends TestCase
$grant = new ImplicitGrant(new \DateInterval('PT10M'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->completeAuthorizationRequest($authRequest);

View File

@@ -13,16 +13,12 @@ use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\RefreshTokenEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class PasswordGrantTest extends TestCase
class PasswordGrantTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
public function testGetIdentifier()
{
$userRepositoryMock = $this->getMockBuilder(UserRepositoryInterface::class)->getMock();
@@ -50,16 +46,13 @@ class PasswordGrantTest extends TestCase
$refreshTokenRepositoryMock->method('persistNewRefreshToken')->willReturnSelf();
$refreshTokenRepositoryMock->method('getNewRefreshToken')->willReturn(new RefreshTokenEntity());
$scope = new ScopeEntity();
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$grant = new PasswordGrant($userRepositoryMock, $refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody(
@@ -74,8 +67,8 @@ class PasswordGrantTest extends TestCase
$responseType = new StubResponseType();
$grant->respondToAccessTokenRequest($serverRequest, $responseType, new \DateInterval('PT5M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $responseType->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $responseType->getRefreshToken());
$this->assertTrue($responseType->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($responseType->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**

View File

@@ -16,13 +16,12 @@ use LeagueTests\Stubs\CryptTraitStub;
use LeagueTests\Stubs\RefreshTokenEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequest;
class RefreshTokenGrantTest extends TestCase
class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
{
/**
* @var CryptTraitStub
* CryptTrait stub
*/
protected $cryptStub;
@@ -46,24 +45,27 @@ class RefreshTokenGrantTest extends TestCase
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);
$scopeEntity = new ScopeEntity();
$scopeEntity->setIdentifier('foo');
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeEntity = new ScopeEntity();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scopeEntity);
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('getNewToken')->willReturn(new AccessTokenEntity());
$accessTokenRepositoryMock->expects($this->once())->method('persistNewAccessToken')->willReturnSelf();
$accessTokenRepositoryMock
->expects($this->once())
->method('persistNewAccessToken')->willReturnSelf();
$refreshTokenRepositoryMock = $this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock();
$refreshTokenRepositoryMock->method('getNewRefreshToken')->willReturn(new RefreshTokenEntity());
$refreshTokenRepositoryMock->expects($this->once())->method('persistNewRefreshToken')->willReturnSelf();
$refreshTokenRepositoryMock
->expects($this->once())
->method('persistNewRefreshToken')->willReturnSelf();
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(
@@ -80,18 +82,19 @@ class RefreshTokenGrantTest extends TestCase
);
$serverRequest = new ServerRequest();
$serverRequest = $serverRequest->withParsedBody([
'client_id' => 'foo',
'client_secret' => 'bar',
'refresh_token' => $oldRefreshToken,
'scopes' => ['foo'],
]);
$serverRequest = $serverRequest->withParsedBody(
[
'client_id' => 'foo',
'client_secret' => 'bar',
'refresh_token' => $oldRefreshToken,
]
);
$responseType = new StubResponseType();
$grant->respondToAccessTokenRequest($serverRequest, $responseType, new \DateInterval('PT5M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $responseType->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $responseType->getRefreshToken());
$this->assertTrue($responseType->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($responseType->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
public function testRespondToReducedScopes()
@@ -118,7 +121,7 @@ class RefreshTokenGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(
@@ -147,8 +150,8 @@ class RefreshTokenGrantTest extends TestCase
$responseType = new StubResponseType();
$grant->respondToAccessTokenRequest($serverRequest, $responseType, new \DateInterval('PT5M'));
$this->assertInstanceOf(AccessTokenEntityInterface::class, $responseType->getAccessToken());
$this->assertInstanceOf(RefreshTokenEntityInterface::class, $responseType->getRefreshToken());
$this->assertTrue($responseType->getAccessToken() instanceof AccessTokenEntityInterface);
$this->assertTrue($responseType->getRefreshToken() instanceof RefreshTokenEntityInterface);
}
/**
@@ -177,7 +180,7 @@ class RefreshTokenGrantTest extends TestCase
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(
@@ -224,7 +227,7 @@ class RefreshTokenGrantTest extends TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$serverRequest = new ServerRequest();
@@ -256,7 +259,7 @@ class RefreshTokenGrantTest extends TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = 'foobar';
@@ -288,13 +291,14 @@ class RefreshTokenGrantTest extends TestCase
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('persistNewAccessToken')->willReturnSelf();
$refreshTokenRepositoryMock = $this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock();
$refreshTokenRepositoryMock->method('persistNewRefreshToken')->willReturnSelf();
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(
@@ -340,7 +344,7 @@ class RefreshTokenGrantTest extends TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(
@@ -387,7 +391,7 @@ class RefreshTokenGrantTest extends TestCase
$grant = new RefreshTokenGrant($refreshTokenRepositoryMock);
$grant->setClientRepository($clientRepositoryMock);
$grant->setAccessTokenRepository($accessTokenRepositoryMock);
$grant->setEncryptionKey($this->cryptStub->getKey());
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$oldRefreshToken = $this->cryptStub->doEncrypt(

View File

@@ -11,24 +11,18 @@ use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
class AuthorizationServerMiddlewareTest extends TestCase
class AuthorizationServerMiddlewareTest extends \PHPUnit_Framework_TestCase
{
const DEFAULT_SCOPE = 'basic';
public function testValidResponse()
{
$clientRepository = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepository->method('getClientEntity')->willReturn(new ClientEntity());
$scopeEntity = new ScopeEntity;
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scopeEntity);
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);
$accessRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
@@ -39,11 +33,11 @@ class AuthorizationServerMiddlewareTest extends TestCase
$accessRepositoryMock,
$scopeRepositoryMock,
'file://' . __DIR__ . '/../Stubs/private.key',
base64_encode(random_bytes(36)),
'file://' . __DIR__ . '/../Stubs/public.key',
new StubResponseType()
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$server->setDefaultScope(self::DEFAULT_SCOPE);
$server->enableGrantType(new ClientCredentialsGrant());
$_POST['grant_type'] = 'client_credentials';
@@ -73,9 +67,10 @@ class AuthorizationServerMiddlewareTest extends TestCase
$this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock(),
$this->getMockBuilder(ScopeRepositoryInterface::class)->getMock(),
'file://' . __DIR__ . '/../Stubs/private.key',
base64_encode(random_bytes(36)),
'file://' . __DIR__ . '/../Stubs/public.key',
new StubResponseType()
);
$server->setEncryptionKey(base64_encode(random_bytes(36)));
$server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M'));
@@ -104,8 +99,7 @@ class AuthorizationServerMiddlewareTest extends TestCase
$response = $exception->generateHttpResponse(new Response());
$this->assertEquals(302, $response->getStatusCode());
$this->assertEquals('http://foo/bar?error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope',
$response->getHeader('location')[0]);
$this->assertEquals('http://foo/bar?error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope', $response->getHeader('location')[0]);
}
public function testOAuthErrorResponseRedirectUriFragment()
@@ -114,7 +108,6 @@ class AuthorizationServerMiddlewareTest extends TestCase
$response = $exception->generateHttpResponse(new Response(), true);
$this->assertEquals(302, $response->getStatusCode());
$this->assertEquals('http://foo/bar#error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope',
$response->getHeader('location')[0]);
$this->assertEquals('http://foo/bar#error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope', $response->getHeader('location')[0]);
}
}

View File

@@ -8,11 +8,10 @@ use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\ResourceServer;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\ClientEntity;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
class ResourceServerMiddlewareTest extends TestCase
class ResourceServerMiddlewareTest extends \PHPUnit_Framework_TestCase
{
public function testValidResponse()
{

View File

@@ -1,39 +0,0 @@
<?php
declare(strict_types = 1);
namespace LeagueTests\PHPStan;
use League\OAuth2\Server\Grant\AbstractGrant;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\NullType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
final class AbstractGrantExtension implements DynamicMethodReturnTypeExtension
{
public function getClass(): string
{
return AbstractGrant::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return in_array($methodReflection->getName(), [
'getRequestParameter',
'getQueryStringParameter',
'getCookieParameter',
], true);
}
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
return TypeCombinator::union(...[
new StringType(),
isset($methodCall->args[2]) ? $scope->getType($methodCall->args[2]->value) : new NullType(),
]);
}
}

View File

@@ -6,10 +6,9 @@ namespace LeagueTests;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\ResourceServer;
use PHPUnit\Framework\TestCase;
use Zend\Diactoros\ServerRequestFactory;
class ResourceServerTest extends TestCase
class ResourceServerTest extends \PHPUnit_Framework_TestCase
{
public function testValidateAuthenticatedRequest()
{

View File

@@ -11,18 +11,19 @@ use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\ClientEntity;
use LeagueTests\Stubs\RefreshTokenEntity;
use LeagueTests\Stubs\ScopeEntity;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
class BearerResponseTypeTest extends TestCase
class BearerResponseTypeTest extends \PHPUnit_Framework_TestCase
{
public function testGenerateHttpResponse()
{
$responseType = new BearerTokenResponse();
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$client = new ClientEntity();
$client->setIdentifier('clientName');
@@ -46,7 +47,7 @@ class BearerResponseTypeTest extends TestCase
$response = $responseType->generateHttpResponse(new Response());
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertTrue($response instanceof ResponseInterface);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('no-cache', $response->getHeader('pragma')[0]);
$this->assertEquals('no-store', $response->getHeader('cache-control')[0]);
@@ -54,17 +55,19 @@ class BearerResponseTypeTest extends TestCase
$response->getBody()->rewind();
$json = json_decode($response->getBody()->getContents());
$this->assertAttributeEquals('Bearer', 'token_type', $json);
$this->assertObjectHasAttribute('expires_in', $json);
$this->assertObjectHasAttribute('access_token', $json);
$this->assertObjectHasAttribute('refresh_token', $json);
$this->assertEquals('Bearer', $json->token_type);
$this->assertTrue(isset($json->expires_in));
$this->assertTrue(isset($json->access_token));
$this->assertTrue(isset($json->refresh_token));
}
public function testGenerateHttpResponseWithExtraParams()
{
$responseType = new BearerTokenResponseWithParams();
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponseWithParams($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$client = new ClientEntity();
$client->setIdentifier('clientName');
@@ -88,7 +91,7 @@ class BearerResponseTypeTest extends TestCase
$response = $responseType->generateHttpResponse(new Response());
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertTrue($response instanceof ResponseInterface);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('no-cache', $response->getHeader('pragma')[0]);
$this->assertEquals('no-store', $response->getHeader('cache-control')[0]);
@@ -96,20 +99,23 @@ class BearerResponseTypeTest extends TestCase
$response->getBody()->rewind();
$json = json_decode($response->getBody()->getContents());
$this->assertAttributeEquals('Bearer', 'token_type', $json);
$this->assertObjectHasAttribute('expires_in', $json);
$this->assertObjectHasAttribute('access_token', $json);
$this->assertObjectHasAttribute('refresh_token', $json);
$this->assertEquals('Bearer', $json->token_type);
$this->assertTrue(isset($json->expires_in));
$this->assertTrue(isset($json->access_token));
$this->assertTrue(isset($json->refresh_token));
$this->assertObjectHasAttribute('foo', $json);
$this->assertAttributeEquals('bar', 'foo', $json);
$this->assertTrue(isset($json->foo));
$this->assertEquals('bar', $json->foo);
}
public function testDetermineAccessTokenInHeaderValidToken()
{
$responseType = new BearerTokenResponse();
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(false);
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$client = new ClientEntity();
$client->setIdentifier('clientName');
@@ -135,6 +141,7 @@ class BearerResponseTypeTest extends TestCase
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(false);
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$authorizationValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest();
@@ -151,10 +158,11 @@ class BearerResponseTypeTest extends TestCase
public function testDetermineAccessTokenInHeaderInvalidJWT()
{
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(false);
$responseType = new BearerTokenResponse();
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$client = new ClientEntity();
$client->setIdentifier('clientName');
@@ -177,6 +185,7 @@ class BearerResponseTypeTest extends TestCase
$json = json_decode((string) $response->getBody());
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$authorizationValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest();
@@ -196,7 +205,7 @@ class BearerResponseTypeTest extends TestCase
{
$responseType = new BearerTokenResponse();
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$client = new ClientEntity();
$client->setIdentifier('clientName');
@@ -222,6 +231,7 @@ class BearerResponseTypeTest extends TestCase
$accessTokenRepositoryMock->method('isAccessTokenRevoked')->willReturn(true);
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$authorizationValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest();
@@ -239,13 +249,16 @@ class BearerResponseTypeTest extends TestCase
public function testDetermineAccessTokenInHeaderInvalidToken()
{
$responseType = new BearerTokenResponse();
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$authorizationValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest();
@@ -263,13 +276,16 @@ class BearerResponseTypeTest extends TestCase
public function testDetermineMissingBearerInHeader()
{
$responseType = new BearerTokenResponse();
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$responseType = new BearerTokenResponse($accessTokenRepositoryMock);
$responseType->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$responseType->setEncryptionKey(base64_encode(random_bytes(36)));
$responseType->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$accessTokenRepositoryMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$authorizationValidator = new BearerTokenValidator($accessTokenRepositoryMock);
$authorizationValidator->setPrivateKey(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));
$authorizationValidator->setPublicKey(new CryptKey('file://' . __DIR__ . '/../Stubs/public.key'));
$request = new ServerRequest();

View File

@@ -1 +0,0 @@
private.key.crlf text eol=crlf

View File

@@ -2,6 +2,7 @@
namespace LeagueTests\Stubs;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\CryptTrait;
class CryptTraitStub
@@ -10,12 +11,8 @@ class CryptTraitStub
public function __construct()
{
$this->setEncryptionKey(base64_encode(random_bytes(36)));
}
public function getKey()
{
return $this->encryptionKey;
$this->setPrivateKey(new CryptKey('file://' . __DIR__ . '/private.key'));
$this->setPublicKey(new CryptKey('file://' . __DIR__ . '/public.key'));
}
public function doEncrypt($unencryptedData)

View File

@@ -1,27 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtHYxRBYATiiyDFs3pEhFg6Ei/UiQEmolTaQyQK810xHY23+X
4elLl6HP1J09mefmJ3ZdIgjIOS6rfK1BQnZIvI+IkoC7+qpD92y9f48iL0tCYKsn
i1LFFjP0bESTGDe7XANifQPkp9GvKgJbu7h1/ac8x4CBSU0ZjtEvinQRsdYil6OM
MXLWGozbBy13X8G+Ganv2i1aPZ2B25GyrH6lVIEwztGrSYxUrFVL+8dHhONf6PYX
19gjdzxkXCYQy2AGMc1FevZmnpIqDNQwX7CUUXQ4TDJmiP0aBEni094gUhnRFUr9
dmGpLQcCb2i0WMh2K+swFk3EutDAJ+73LKoZ3QIDAQABAoIBADo8Tge3xd9zGIoO
QbV9MRmaPW1ZJk0a/fDBRQpEwGzdvIqQ8VWQ8Lj9GdF18LQi9s3TT5i1FtAFNIfm
bUHiY/SdqSgF7SOmIIrPB5QLf6+dbM0/TmKSklFo8L6jnohZK9g0q2rGf9p8Ozem
TS4WB9WUS3PiD1a1T8Mb1Gisri0h7rvI4TIkrcx6lUUCgphCZd2TWUhmE3YmybOg
4h855W685g/ydzjwB+5Y6CS3V6a78Z5Gb4df3l0XfqCWh/xzuNs7nIpRv8CE0vRE
vq9j/cVyKkzMjiagteJaisTCBkDmtAi9dEVL8uaSDoTJq1g+VOGuJxHUm31Pavqr
3RwvXS0CgYEA74jUqmzxAwr/uBWquIkfMg+hsKjJe3gsSAJIAPzcA9OkzZd9w/1R
P8C92N2UaDbCW7ZEl7ZzS+IO6nA4OcR98j77/nBk6cYykyVRkSaj01epz3bRApxc
R18e49MBftSMnI5R7lIJO/UAIRfd0rntX4jkdVAdn9s/VOvG8w4KQXcCgYEAwN3W
b3azSNYlj4CW8+t6qS/3JQ/qpPgVuqkqP9dQXC9O6VlV03pJIwFk2Ldjd7/eXT+0
hFVB3O71iECfet/1UgustlgFp5I4ZrPmYF/J1nGpx1KIE8P4d0qC8lODtdnsGAcU
+/vBjXinX7pWgM8e6LAJzqNUq/xal/wNY325dEsCgYB7J0+n+/ECToJhhApNbHq0
g2LvcCh/Ka8iqsGYeGkqMoOWDKBlxvUiIRe6y1nFJvpQquqjUfP/fM+Ma3wM/2B9
zzJChEjuBK/2BYblaQdr3rN47i7R99BeBaLdIZywN9m/mFC5hkYnJHUXjqzG7j8E
El7bjgBdMx1hrQOR7ZMKSwKBgQC2SXXBiBlPwEdj6I/EH06h1hnrR63pGim/cN/j
0ye62WPmHW+HH888bLbaNgqnRgtvayS85rAHlzst+pZBVqfRUgN9nJhLl2IDgAlA
EYj9TBTBtXmz5MdUSHKXguO73yrMUvU8bOi1Q9I+IipcOGboWmoKikke/LbLa4lj
/ZJpHQKBgQCuDanU+AJKgUQkkC2gHwT8quxPoRcFFErHp3iaDAwd5XsZJG9FHQUP
RkPE+JkSaj65byFLhCPHUayfk4Y4udHEy4cXiv2SxZNK8q1HwuFEvb7uFprj0hNs
14qJunONVt/jzswdwO5kGVbpGlHl7U0JABnTJP71fW/rE5SH4zYxqg==
-----END RSA PRIVATE KEY-----

View File

@@ -1,41 +0,0 @@
<?php
namespace LeagueTests\Utils;
use Defuse\Crypto\Key;
use LeagueTests\Stubs\CryptTraitStub;
use PHPUnit\Framework\TestCase;
class CryptTraitTest extends TestCase
{
protected $cryptStub;
protected function setUp()
{
$this->cryptStub = new CryptTraitStub();
}
public function testEncryptDecryptWithPassword()
{
$this->cryptStub->setEncryptionKey(base64_encode(random_bytes(36)));
$this->encryptDecrypt();
}
public function testEncryptDecryptWithKey()
{
$this->cryptStub->setEncryptionKey(Key::createNewRandomKey());
$this->encryptDecrypt();
}
private function encryptDecrypt()
{
$payload = 'alex loves whisky';
$encrypted = $this->cryptStub->doEncrypt($payload);
$plainText = $this->cryptStub->doDecrypt($encrypted);
$this->assertNotEquals($payload, $encrypted);
$this->assertEquals($payload, $plainText);
}
}