Compare commits

...

143 Commits
4.0.0 ... 4.1.x

Author SHA1 Message Date
Andrew Millington
138524984a Merge pull request #918 from Sephster/fix-914
Fix empty issue in PHP 5.4
2018-06-23 17:27:31 +01:00
sephster
8335935854 Fix empty issue in PHP 5.4 2018-06-22 13:47:22 +01:00
Alex Bilbie
3bec591393 Changelog update 2016-09-13 14:42:53 +01:00
Alex Bilbie
084b779cc6 Merge pull request #652 from rickshawhobo/4.1.x
less restrictive on Authorization header check
2016-09-13 14:38:47 +01:00
Guy Huynh
491f3f0e95 less restrictive on Authorization header check 2016-09-08 10:20:34 -04:00
Alex Bilbie
c5db707e69 Updated changelog 2016-01-04 19:56:12 +00:00
Alex Bilbie
ed7f78179a Merge pull request #412 from derrabus/symfony-3
Allow Symfony 3.0
2015-12-20 20:38:02 +00:00
Alexander M. Turek
6e92239dd7 Allow Symfony 3.0. 2015-12-11 15:24:13 +01:00
Alex Bilbie
f5d731def9 Updated changelog 2015-11-13 17:52:27 +00:00
Alex Bilbie
03815cec6d Merge pull request #388 from m4tthumphrey/master
Added priority argument
2015-10-13 11:21:52 +01:00
Matt Humphrey
c71dc47459 Added priority argument 2015-10-13 11:16:49 +01:00
Alex Bilbie
3bcd8fc3f8 Removed runs and increased timeout 2015-09-26 11:26:17 +01:00
Alex Bilbie
db6d4e0dc6 Only send data to Scrutinizer only for PHP 5.6 2015-09-26 11:25:26 +01:00
Alex Bilbie
f19189a999 Merge pull request #345 from mpipet/master
Expose parameter passed to exceptions
2015-09-04 08:38:35 +01:00
Alex Bilbie
ec9c91cc11 Update .scrutinizer.yml 2015-09-04 08:37:12 +01:00
Alex Bilbie
c3457107ee Merge pull request #370 from michaelhogg/fix-bug-hmac-encoding
Fix bug: hash_hmac() should output raw binary data, not hexits
2015-09-04 08:36:33 +01:00
Alex Bilbie
a9f61fd3ed Merge pull request #377 from starJammer/master
AuthCodeGrant and RefreshTokenGrant don't require client_secret
2015-09-04 08:29:39 +01:00
Alex Bilbie
b78d8ca1d8 Merge pull request #364 from apollopy/master
Too idealistic. Should allow the client and server have some time difference.
2015-09-04 08:28:14 +01:00
Jerry Saravia
8f82e8ef86 Added test for setRequireClientSecret 2015-09-03 23:16:09 -04:00
Jerry Saravia
d88e01c7dd Making client secret optional during refresh and access token requsets. 2015-09-03 22:50:35 -04:00
Michael Hogg
d21374fb0b Merge remote-tracking branch 'thephpleague/master' into fix-bug-hmac-encoding 2015-09-02 09:50:46 +01:00
Alex Bilbie
31e5f4d33c Merge pull request #368 from apollopy/mac_token_only_header
Mac token only get to header
2015-09-01 14:33:58 +01:00
Alex Bilbie
a773405adf Merge pull request #369 from joaopramos/mac-refresh-tokens
Mac refresh tokens
2015-09-01 14:32:45 +01:00
Alex Bilbie
ccc845b195 Merge pull request #371 from michaelhogg/fix-bug-base64-regex
Fix bug: regex doesn't match all Base64 characters
2015-09-01 14:30:38 +01:00
Alex Bilbie
21cd917892 Merge pull request #372 from michaelhogg/fix-bug-request-uri
Fix bug: incorrect signature parameter
2015-09-01 14:29:41 +01:00
Michael Hogg
a2c418ee07 Fix bug: incorrect signature parameter 2015-08-28 16:41:12 +01:00
Michael Hogg
b220368583 Fix bug: regex doesn't match all Base64 characters 2015-08-28 14:01:22 +01:00
Michael Hogg
2d26c38d6c Update unit test: testDetermineAccessTokenInHeaderValid() 2015-08-28 13:11:20 +01:00
Michael Hogg
eeaa68400f Fix bug: hash_hmac() should output raw binary data, not hexits 2015-08-28 12:46:53 +01:00
joao
56c73d2427 ISSUE #356: added the refresh token to the mac token type response 2015-08-28 10:40:13 +00:00
joao
f632fcc997 ISSUE #356: added the refresh token to the mac token type response 2015-08-28 10:38:45 +00:00
ApolloPY
618d84ddcf Mac token only get to header 2015-08-22 01:47:59 +08:00
apollopy
ace42e89e0 change to 300 seconds 2015-08-21 20:02:42 +08:00
ApolloPY
c496df98e4 Too idealistic. Should allow the client and server have some time difference. 2015-08-21 17:17:51 +08:00
Alex Bilbie
2496653968 Merge pull request #342 from gaomd/master
Fix #328, strict check Bearer token
2015-08-21 09:00:02 +01:00
Alex Bilbie
abf66ef9c8 Merge pull request #346 from Korri/Korri-patch-removed-duplicate-routing
Removed duplicate routing setup code
2015-08-21 08:59:35 +01:00
Alex Bilbie
4b9ec488f4 Merge pull request #352 from daveblake/master
Fix typo in docblock
2015-07-13 21:55:43 +01:00
DavidBlake
726d879607 Fix typo in docblock 2015-06-18 13:27:58 +01:00
Mathieu Pipet
b256195421 Expose parameter passed to exceptions 2015-06-09 17:42:25 +02:00
Mathieu Pipet
c84ea1ea62 Expose parameter passed to exceptions 2015-06-09 17:30:13 +02:00
Hugo Vacher
16685ccde4 Removed duplicate routing setup code 2015-06-08 15:50:55 -04:00
Mengdi Gao
7934c7bb53 Fix #328, strict check Bearer token 2015-06-01 21:36:44 +08:00
Alex Bilbie
c174b6fc65 Merge pull request #341 from thephpleague/philsturgeon-patch-1
Added integration list to readme
2015-05-20 13:22:42 +01:00
Phil Sturgeon
75ced70248 Added integration list to readme
I figure it's a good idea to let people know where they can find their bridge packages to save em looking or building their own framework specific nonsense.
2015-05-17 13:33:50 -04:00
Alex Bilbie
5b7fdaeece Merge pull request #330 from jakeasmith/patch-1
Just a typo fix
2015-04-16 17:48:00 +01:00
Jake A. Smith
430a752315 Just a typo fix 2015-04-16 10:41:37 -05:00
Alex Bilbie
810544ec0a Changelog update 2015-03-22 23:32:45 +00:00
Alex Bilbie
34a6b66b8c More .travis.yml updates 2015-03-22 23:19:36 +00:00
Alex Bilbie
61738a7fe2 Added fast_finish: true to .travis.yml 2015-03-22 23:13:41 +00:00
Alex Bilbie
51184259d1 Merge pull request #323 from rdohms/interface-docs
Updated Interface Docs
2015-03-20 11:43:47 +00:00
rdohms
b21de11429 Updated Interface Docs
Made phpdocs match expectations like null when not found and using array notation for indicating array of <object>
2015-03-20 11:33:03 +01:00
Alex Bilbie
cf6e86c9d4 Merge pull request #319 from Fuxy22/patch-1
Fixed missing session scope
2015-03-13 11:03:05 +00:00
Alex Bilbie
f6fdbc7142 Added PHP 7.0 testing 2015-03-03 22:00:47 +00:00
Norbert Fuksz
7f7f45662a Fixed missing session scope
Close #297
2015-03-02 17:47:48 +00:00
Alex Bilbie
f92a68cc72 Merge branch 'master' of github.com:thephpleague/oauth2-server 2015-02-22 19:47:44 +00:00
Alex Bilbie
295d8ffa24 Updated league/event to ~2.1. Fixes #311 2015-02-22 19:47:27 +00:00
Alex Bilbie
3d08140651 Merge pull request #300 from vvllaadd/patch-2
Probable bug
2015-02-22 19:45:14 +00:00
Alex Bilbie
ec8a8393ee Merge pull request #310 from ismailbaskin/master
typo
2015-02-10 10:03:53 +00:00
Ismail BASKIN
3869b8f406 typo 2015-02-10 10:28:57 +02:00
Alex Bilbie
7da7484008 Added security section 2015-02-05 16:14:59 +00:00
Alex Bilbie
b42ba4af17 Merge pull request #303 from hannesvdvreken/fix/consistent-use-and-fqcn
Boyscouting the php docs to always use FQCNs
2015-01-23 10:47:26 +00:00
Hannes Van De Vreken
dd795a82f4 Changed the order and added missing throws 2015-01-23 11:21:12 +01:00
Hannes Van De Vreken
166362d3cd Boyscouting the php docs to always use FQCNs 2015-01-23 11:17:19 +01:00
Vlad
d43391564c Probable bug
AccessTokenStorage::delete should delete the token, not the scope associated with the token
2015-01-15 14:20:54 +01:00
Alex Bilbie
ea6edf572a Changelog update 2015-01-01 12:56:20 +00:00
Alex Bilbie
19b64c2e65 Merge pull request #290 from sarciszewski/patch-1
Remove side-effects in hash_equals()
2015-01-01 12:52:03 +00:00
Scott Arciszewski
612775466c Remove side-effects in hash_equals()
This is functionally identical, but without the side-effect of defining a function in the current namespace.

Also, it uses absolute function reference (`\hash_equals` instead of `hash_equals`) because if someone defined `League\OAuth2\Server\TokenType\hash_equals()` elsewhere, it would try that first.

Kudos for using `hash_equals()` in your original design for this feature. Many OAuth2 implementations neglect this nuance :)
2015-01-01 01:34:22 -05:00
Alex Bilbie
740ea24e08 Changelog update 2014-12-31 16:03:26 +00:00
Alex Bilbie
e1c14abf6c Lowered symfony/http-foundation to ~2.4 so Laravel can use it 2014-12-31 15:51:52 +00:00
Alex Bilbie
d1aae27359 Version bump 2014-12-27 23:01:11 +00:00
Alex Bilbie
80aeaf9200 Merge branch 'Symplicity-master' into release/4.1.0 2014-12-27 23:00:17 +00:00
Alex Bilbie
282bb20cc8 Fix docblocks + method name 2014-12-27 23:00:11 +00:00
Alex Bilbie
b727be55a2 Merge branch 'master' of https://github.com/Symplicity/oauth2-server into Symplicity-master 2014-12-27 22:57:08 +00:00
Alex Bilbie
cf80a2d6ce README update 2014-12-27 22:55:30 +00:00
Alex Bilbie
72a5c1794a Remove unused namespace 2014-12-27 22:50:13 +00:00
Alex Bilbie
707c85b0d6 Fixes and tests 2014-12-27 22:26:31 +00:00
Alex Bilbie
c56562b0b8 PSR fixes 2014-12-27 21:38:01 +00:00
Alex Bilbie
d0b2498b43 Ignore PHPStorm 2014-12-27 21:35:45 +00:00
Alex Bilbie
17be6f4549 Added MacTokenInterface 2014-12-27 21:35:45 +00:00
Alex Bilbie
b50fbff1e3 Update docblock 2014-12-27 21:35:45 +00:00
Alex Bilbie
7375a348c6 PHP code fix 2014-12-27 21:35:45 +00:00
Alex Bilbie
ae5dd9ce65 Added MAC TokenType 2014-12-27 21:35:45 +00:00
Alex Bilbie
f9e56ff62a Added MAC storage getter and setter 2014-12-27 21:35:45 +00:00
Alex Bilbie
1bcf7ee20f Update .travis.yml 2014-12-26 17:03:35 +00:00
Alex Bilbie
bee9c6a51d Added Gitter.im 2014-12-26 16:59:09 +00:00
Dave Walker
851c7c0eb1 Per the spec:
The authorization server MAY issue a new refresh token, in which case
   the client MUST discard the old refresh token and replace it with the
   new refresh token.  The authorization server MAY revoke the old
   refresh token after issuing a new refresh token to the client.  If a
   new refresh token is issued, the refresh token scope MUST be
   identical to that of the refresh token included by the client in the
   request.

This commit allows users to specifiy the time before the Refresh Token
expire time to issue a new Refresh Token.

alter method names, naming convention(?)
2014-12-21 18:51:52 -05:00
Alex Bilbie
7fff4a8fe8 Merge pull request #280 from danprime/master
Fix Example Init Code
2014-12-17 10:10:50 +00:00
Alex Bilbie
44ac01ee0e Merge pull request #284 from mortenhauberg/fix-misspelling
Changed "paremter" to "parameter"
2014-12-16 19:48:40 +00:00
mortenhauberg
60bd334b46 Changed "paremter" to "parameter" 2014-12-16 19:04:03 +01:00
Alex Bilbie
7398bee59e Version bump 2014-12-15 17:34:38 +00:00
Alex Bilbie
40420f27ed Merge pull request #282 from maknz/master
Prevent duplicate session in auth code grant
2014-12-15 16:27:02 +00:00
Regan
d32bfaa757 Prevent duplicate session in auth code grant
The session already exists in the database, so we don't need to save it again. Doing so results in the session used for the auth code hanging around in the database with nothing associated to it, while the access token is associated to a new session caused by the `save()` method creating a duplicate. Fixes #266.
2014-12-15 15:09:36 +13:00
Daniel Tse
2653a174bb Update init.php 2014-12-12 10:25:52 -07:00
Daniel Tse
676fb4c06a Fix column declarations and references so that foreign keys and references work. 2014-12-11 15:50:42 -07:00
Alex Bilbie
7f815275d6 Fixes for .travis.yml 2014-12-11 14:25:35 +00:00
Alex Bilbie
a056e2fe03 Adding coverage to ghpages 2014-12-11 14:20:53 +00:00
Alex Bilbie
48d9fde133 Merge pull request #277 from GrahamCampbell/patch-1
Removed an extra new line
2014-12-10 15:19:50 +00:00
Graham Campbell
a12786cbd5 Removed an extra new line 2014-12-10 15:18:49 +00:00
Alex Bilbie
164cc6ddb9 Merge pull request #269 from Hywan/fix_example_api
Fix bad accesses and bad arguments
2014-12-10 15:13:10 +00:00
Alex Bilbie
27f51d33e1 Merge pull request #271 from inverse/example-fix
Example fix
2014-12-10 15:12:40 +00:00
Alex Bilbie
2108c88dfb Merge pull request #276 from GrahamCampbell/cs
CS Fixes
2014-12-10 15:12:16 +00:00
Graham Campbell
a1726903b5 CS fixes 2014-12-10 13:10:35 +00:00
Alex Bilbie
8075190e0c Merge pull request #275 from Hywan/cs
Fix API CS.
2014-12-10 09:58:06 +00:00
Ivan Enderlin
3b176fe220 Fix API CS. 2014-12-09 14:40:39 +01:00
Ivan Enderlin
986dc59627 The create method returns void. 2014-12-09 14:40:39 +01:00
Ivan Enderlin
0878897969 Fix API CS. 2014-12-09 14:15:36 +01:00
Alex Bilbie
0ce7ecb45a Merge pull request #273 from sarciszewski/patch-1
Make Util/KeyAlgorithm/DefaultAlgorithm guarantee $len bytes of output even in edge cases.
2014-12-09 12:53:04 +00:00
Scott Arciszewski
7a63f42462 Update DefaultAlgorithm.php
Prevent edge-case whereby, if the majority of `base64_encode($bytes)` consists of `/` or `+` characters, the resulting key will be shorter and less unpredictable (due to a smaller keyspace) than anticipated.

As a result, the `$len * 2` hack has been removed. Although it is highly probable that `$len * 2` will stop most edge cases from occurring, it does not actually guarantee the end result will be at least 40 characters long.
2014-12-08 18:40:31 -05:00
Malachi Soord
774341c346 Fixed tokeninfo 2014-12-05 18:24:24 +01:00
Malachi Soord
c8983b35a0 Fixed example API hasScope reference 2014-12-05 18:12:19 +01:00
Alex Bilbie
edaccab04b Changelog update 2014-12-03 23:25:45 +00:00
Alex Bilbie
f8b61b47b9 Ensure Refresh Token Entity hasn't expired 2014-12-03 23:22:14 +00:00
Alex Bilbie
b8331d12e4 Syntax improvements 2014-12-03 23:21:54 +00:00
Alex Bilbie
92404ab2bf Merge branch 'master' of github.com:thephpleague/oauth2-server 2014-12-03 22:56:05 +00:00
Ivan Enderlin
3b17872f10 Fix bad accesses and bad arguments. 2014-12-02 11:54:45 +01:00
Alex Bilbie
8cfa3dcdad Changelog update 2014-12-02 10:45:18 +00:00
Alex Bilbie
9ec1380889 Merge pull request #268 from Hywan/fix_example_storage_authcode
Do not forget to set the expire time
2014-12-02 10:37:05 +00:00
Ivan Enderlin
2af7195f06 Do not forget to set the expire time. 2014-12-02 11:28:55 +01:00
Alex Bilbie
8c6fd6c05a Merge pull request #267 from Hywan/fix_examples
Fix bad type hintings
2014-12-02 10:05:41 +00:00
Ivan Enderlin
2df6446eb2 Fix bad type hintings. 2014-12-02 10:20:55 +01:00
Alex Bilbie
e1c0ff2685 Code coverage improvements in grant classes 2014-11-23 23:32:50 +00:00
Alex Bilbie
6157bd77ca Changelog update 2014-11-21 00:19:43 +00:00
Alex Bilbie
76de634f2b Added setSession on TokenTypeInterface as per #255 2014-11-21 00:06:17 +00:00
Alex Bilbie
cfada388db Declared methods from AbstractGrant on GrantTypeInterface as per #255 2014-11-21 00:06:01 +00:00
Alex Bilbie
2f971dc77f Declared all of the methods in AbstractTokenType in TokenTypeInterface as per #255 2014-11-20 23:54:52 +00:00
Alex Bilbie
ae7b7e9aa9 Fixed namespace includes 2014-11-20 23:54:14 +00:00
Alex Bilbie
bed6c3287e Spelling fixes 2014-11-20 23:53:14 +00:00
Alex Bilbie
f83e5a8731 Learnt how to spell delimiter 2014-11-20 23:52:29 +00:00
Alex Bilbie
35369038db Merge pull request #254 from bajb/master
Docbloc improvements
2014-11-13 12:37:20 +00:00
Brooke Bryan
6a1f927a6c Check refreshToken isset before attempting to call methods on it 2014-11-13 12:20:59 +00:00
Brooke Bryan
b2c0933ee6 Docbloc improvements 2014-11-12 18:10:29 +00:00
Alex Bilbie
3104d13eba Merge pull request #253 from bajb/master
Update Adapter to AbstractStorage in examples/relational
2014-11-12 10:43:31 +00:00
Brooke Bryan
8b1f3ef193 Update Adapter to AbstractStorage in examples/relational 2014-11-12 10:38:09 +00:00
Alex Bilbie
1ff885cff1 Removed branch alias. Fixes #251 2014-11-11 18:03:42 +00:00
Alex Bilbie
d950797bd9 CHANGELOG update 2014-11-09 11:47:02 +00:00
Alex Bilbie
d6e6b8b710 Merge pull request #246 from lucadegasperi/patch-3
Update ResourceServer.php
2014-11-09 09:12:38 +00:00
Luca Degasperi
001c15bfad Update ResourceServer.php 2014-11-09 09:45:20 +01:00
Alex Bilbie
7fbc563524 Merge pull request #245 from GrahamCampbell/patch-1
Update .travis.yml
2014-11-08 19:12:57 +00:00
Graham Campbell
0d949d53f3 Update .travis.yml 2014-11-08 18:36:59 +00:00
Alex Bilbie
d071cd112a Merge pull request #244 from GrahamCampbell/cs
CS Fixes
2014-11-08 18:35:08 +00:00
Graham Campbell
4c1cd04a24 CS fixes 2014-11-08 18:26:12 +00:00
Alex Bilbie
30162c8899 Merge pull request #243 from GrahamCampbell/patch-1
Alias the master branch
2014-11-08 18:07:00 +00:00
Graham Campbell
b21aac0ab2 Alias the master branch 2014-11-08 18:06:18 +00:00
96 changed files with 1925 additions and 817 deletions

3
.gitignore vendored
View File

@@ -11,4 +11,5 @@
/tests/codecept/tests/_log
oauth2-server.paw
/output_*/
/_site
/_site
.idea

View File

@@ -21,8 +21,7 @@ checks:
fix_doc_comments: true
tools:
external_code_coverage:
timeout: 600
runs: 3
timeout: 1800
php_code_coverage: false
php_code_sniffer:
config:
@@ -34,4 +33,4 @@ tools:
excluded_dirs: [vendor, tests, examples]
php_cpd:
enabled: true
excluded_dirs: [vendor, tests, examples]
excluded_dirs: [vendor, tests, examples]

View File

@@ -1,19 +1,56 @@
language: php
sudo: false
cache:
directories:
- vendor
php:
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
matrix:
allow_failures:
- php: 7.0
fast_finish: true
before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
install:
- travis_retry composer install --no-interaction --prefer-source
script:
- mkdir -p build/logs
- phpunit --coverage-text --verbose --coverage-clover=coverage.clover
- phpunit --coverage-text --verbose --coverage-clover=coverage.clover --coverage-html coverage
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover
- bash -c 'if [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi;
- bash -c 'if [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi;
- git config --global user.email "travis@travis-ci.org"
- git config --global user.name "TravisCI"
- cp -R coverage ${HOME}/coverage
- cd ${HOME}
- git clone --quiet --branch=gh-pages https://${GITHUBTOKEN}@github.com/thephpleague/oauth2-server.git gh-pages > /dev/null
- cd gh-pages
- mkdir ${TRAVIS_BRANCH}
- cd ${TRAVIS_BRANCH}
- cp -Rf $HOME/coverage/* .
- git add -f .
- git commit -m "Travis pushed coverage of ${TRAVIS_COMMIT}@${TRAVIS_BRANCH} to gh-pages"
- git push -fq origin gh-pages > /dev/null
branches:
only:
- master
env:
global:
secure: "C4wD/BQefKSu9W594iyLp+IBCjlM8kKlmp+nXKXnZGi0L8IkV3m4mmNOb8PExxGMhZ3mlev5DnU4Uoh4oJaUxnkR1FpX4dSEpyzU3VknUzSE2yZOlL+bdCw3o85TGoCcp/+ReJCOw5sncxTskJKHlW1YMa33FznaXwLNoImpjTg="
notifications:
webhooks:
urls:
- https://webhooks.gitter.im/e/7de0ca12596cd5268f30
on_success: always # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: false # default: false

View File

@@ -1,5 +1,81 @@
# Changelog
## 4.1.6 (released 2016-09-13)
* Less restrictive on Authorization header check (Issue #652)
## 4.1.5 (released 2016-01-04)
* Enable Symfony 3.0 support (#412)
## 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)
## 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
## 4.1.2 (released 2015-01-01)
* Remove side-effects in hash_equals() implementation (Issue #290)
## 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.*`
## 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
## 4.0.5 (released 2014-12-15)
* Prevent duplicate session in auth code grant (Issue #282)
## 4.0.4 (released 2014-12-03)
* Ensure refresh token hasn't expired (Issue #270)
## 4.0.3 (released 2014-12-02)
* Fix bad type hintings (Issue #267)
* Do not forget to set the expire time (Issue #268)
## 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)
## 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)
## 4.0.0 (released 2014-11-08)
* Complete rewrite

View File

@@ -5,7 +5,7 @@
[![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)
[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-server.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-server) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/thephpleague/oauth2-server?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
A standards compliant [OAuth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource 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.
@@ -22,9 +22,11 @@ You can also define your own grants.
In addition it supports the following token types:
* Bearer tokens
* MAC tokens (coming soon)
* MAC tokens
* JSON web tokens (coming soon)
You can also create you own tokens.
## Requirements
@@ -49,10 +51,19 @@ Contribute to this documentation in the [gh-pages branch](https://github.com/the
Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-server/blob/master/CONTRIBUTING.md) for details.
## Integration
- [CakePHP 3](https://github.com/uafrica/oauth-server)
- [Laravel](https://github.com/lucadegasperi/oauth2-server-laravel)
## Support
Bugs and feature request are tracked on [GitHub](https://github.com/thephpleague/oauth2-server/issues)
## Security
If you discover any security related issues, please email hello@alexbilbie.com instead of using the issue tracker.
## License
This package is released under the MIT License. See the bundled [LICENSE](https://github.com/thephpleague/oauth2-server/blob/master/LICENSE) file for details.

View File

@@ -5,8 +5,8 @@
"license": "MIT",
"require": {
"php": ">=5.4.0",
"symfony/http-foundation": "~2.5",
"league/event": "1.0.*"
"symfony/http-foundation": "~2.4|~3.0",
"league/event": "~2.1"
},
"require-dev": {
"phpunit/phpunit": "4.3.*",
@@ -55,10 +55,5 @@
"psr-4": {
"LeagueTests\\": "tests/unit/"
}
},
"extra": {
"branch-alias": {
"dev-develop": "4.0.x-dev"
}
}
}

View File

@@ -20,6 +20,6 @@ class Users
return $result;
}
return null;
return;
}
}

View File

@@ -2,16 +2,13 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\Adapter;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AbstractTokenEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\AccessTokenInterface;
class AccessTokenStorage extends Adapter implements AccessTokenInterface
class AccessTokenStorage extends AbstractStorage implements AccessTokenInterface
{
/**
* {@inheritdoc}
@@ -30,13 +27,13 @@ class AccessTokenStorage extends Adapter implements AccessTokenInterface
return $token;
}
return null;
return;
}
/**
* {@inheritdoc}
*/
public function getScopes(AbstractTokenEntity $token)
public function getScopes(AccessTokenEntity $token)
{
$result = Capsule::table('oauth_access_token_scopes')
->select(['oauth_scopes.id', 'oauth_scopes.description'])
@@ -50,7 +47,7 @@ class AccessTokenStorage extends Adapter implements AccessTokenInterface
foreach ($result as $row) {
$scope = (new ScopeEntity($this->server))->hydrate([
'id' => $row['id'],
'description' => $row['description']
'description' => $row['description'],
]);
$response[] = $scope;
}
@@ -68,28 +65,28 @@ class AccessTokenStorage extends Adapter implements AccessTokenInterface
->insert([
'access_token' => $token,
'session_id' => $sessionId,
'expire_time' => $expireTime
'expire_time' => $expireTime,
]);
}
/**
* {@inheritdoc}
*/
public function associateScope(AbstractTokenEntity $token, ScopeEntity $scope)
public function associateScope(AccessTokenEntity $token, ScopeEntity $scope)
{
Capsule::table('oauth_access_token_scopes')
->insert([
'access_token' => $token->getId(),
'scope' => $scope->getId()
'scope' => $scope->getId(),
]);
}
/**
* {@inheritdoc}
*/
public function delete(AbstractTokenEntity $token)
public function delete(AccessTokenEntity $token)
{
Capsule::table('oauth_access_token_scopes')
Capsule::table('oauth_access_tokens')
->where('access_token', $token->getId())
->delete();
}

View File

@@ -2,14 +2,13 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use League\OAuth2\Server\Storage\Adapter;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use Illuminate\Database\Capsule\Manager as Capsule;
class AuthCodeStorage extends Adapter implements AuthCodeInterface
class AuthCodeStorage extends AbstractStorage implements AuthCodeInterface
{
/**
* {@inheritdoc}
@@ -25,10 +24,12 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
$token = new AuthCodeEntity($this->server);
$token->setId($result[0]['auth_code']);
$token->setRedirectUri($result[0]['client_redirect_uri']);
$token->setExpireTime($result[0]['expire_time']);
return $token;
}
return null;
return;
}
public function create($token, $expireTime, $sessionId, $redirectUri)
@@ -38,7 +39,7 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
'auth_code' => $token,
'client_redirect_uri' => $redirectUri,
'session_id' => $sessionId,
'expire_time' => $expireTime
'expire_time' => $expireTime,
]);
}
@@ -59,7 +60,7 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
foreach ($result as $row) {
$scope = (new ScopeEntity($this->server))->hydrate([
'id' => $row['id'],
'description' => $row['description']
'description' => $row['description'],
]);
$response[] = $scope;
}
@@ -76,7 +77,7 @@ class AuthCodeStorage extends Adapter implements AuthCodeInterface
Capsule::table('oauth_auth_code_scopes')
->insert([
'auth_code' => $token->getId(),
'scope' => $scope->getId()
'scope' => $scope->getId(),
]);
}

View File

@@ -2,14 +2,13 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\Adapter;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\ClientInterface;
use Illuminate\Database\Capsule\Manager as Capsule;
class ClientStorage extends Adapter implements ClientInterface
class ClientStorage extends AbstractStorage implements ClientInterface
{
/**
* {@inheritdoc}
@@ -36,13 +35,13 @@ class ClientStorage extends Adapter implements ClientInterface
$client = new ClientEntity($this->server);
$client->hydrate([
'id' => $result[0]['id'],
'name' => $result[0]['name']
'name' => $result[0]['name'],
]);
return $client;
}
return null;
return;
}
/**
@@ -60,12 +59,12 @@ class ClientStorage extends Adapter implements ClientInterface
$client = new ClientEntity($this->server);
$client->hydrate([
'id' => $result[0]['id'],
'name' => $result[0]['name']
'name' => $result[0]['name'],
]);
return $client;
}
return null;
return;
}
}

View File

@@ -2,13 +2,12 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\Adapter;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
class RefreshTokenStorage extends Adapter implements RefreshTokenInterface
class RefreshTokenStorage extends AbstractStorage implements RefreshTokenInterface
{
/**
* {@inheritdoc}
@@ -28,7 +27,7 @@ class RefreshTokenStorage extends Adapter implements RefreshTokenInterface
return $token;
}
return null;
return;
}
/**
@@ -40,7 +39,7 @@ class RefreshTokenStorage extends Adapter implements RefreshTokenInterface
->insert([
'refresh_token' => $token,
'access_token' => $accessToken,
'expire_time' => $expireTime
'expire_time' => $expireTime,
]);
}
@@ -53,5 +52,4 @@ class RefreshTokenStorage extends Adapter implements RefreshTokenInterface
->where('refresh_token', $token->getId())
->delete();
}
}

View File

@@ -2,13 +2,12 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Storage\Adapter;
use League\OAuth2\Server\Entity\ScopeEntity;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\ScopeInterface;
class ScopeStorage extends Adapter implements ScopeInterface
class ScopeStorage extends AbstractStorage implements ScopeInterface
{
/**
* {@inheritdoc}
@@ -20,12 +19,12 @@ class ScopeStorage extends Adapter implements ScopeInterface
->get();
if (count($result) === 0) {
return null;
return;
}
return (new ScopeEntity($this->server))->hydrate([
'id' => $result[0]['id'],
'description' => $result[0]['description']
'description' => $result[0]['description'],
]);
}
}

View File

@@ -2,16 +2,15 @@
namespace RelationalExample\Storage;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\Adapter;
use Illuminate\Database\Capsule\Manager as Capsule;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\SessionInterface;
use Illuminate\Database\Capsule\Manager as Capsule;
class SessionStorage extends Adapter implements SessionInterface
class SessionStorage extends AbstractStorage implements SessionInterface
{
/**
* {@inheritdoc}
@@ -32,7 +31,7 @@ class SessionStorage extends Adapter implements SessionInterface
return $session;
}
return null;
return;
}
/**
@@ -54,7 +53,7 @@ class SessionStorage extends Adapter implements SessionInterface
return $session;
}
return null;
return;
}
/**
@@ -74,7 +73,7 @@ class SessionStorage extends Adapter implements SessionInterface
foreach ($result as $scope) {
$scopes[] = (new ScopeEntity($this->server))->hydrate([
'id' => $scope['id'],
'description' => $scope['description']
'description' => $scope['description'],
]);
}
@@ -90,7 +89,7 @@ class SessionStorage extends Adapter implements SessionInterface
->insertGetId([
'owner_type' => $ownerType,
'owner_id' => $ownerId,
'client_id' => $clientId
'client_id' => $clientId,
]);
return $id;
@@ -104,7 +103,7 @@ class SessionStorage extends Adapter implements SessionInterface
Capsule::table('oauth_session_scopes')
->insert([
'session_id' => $session->getId(),
'scope' => $scope->getId()
'scope' => $scope->getId(),
]);
}
}

View File

@@ -1,21 +1,14 @@
<?php
use \Orno\Http\Request;
use \Orno\Http\Response;
use \Orno\Http\JsonResponse;
use \Orno\Http\Exception\NotFoundException;
use \League\OAuth2\Server\ResourceServer;
use \RelationalExample\Storage;
use \RelationalExample\Model;
use Illuminate\Database\Capsule\Manager as Capsule;
use \League\Event\Emitter;
use League\OAuth2\Server\ResourceServer;
use Orno\Http\Exception\NotFoundException;
use Orno\Http\Request;
use Orno\Http\Response;
use RelationalExample\Model;
use RelationalExample\Storage;
include __DIR__.'/vendor/autoload.php';
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$router->setStrategy(\Orno\Route\RouteStrategyInterface::RESTFUL_STRATEGY);
// Set up the OAuth 2.0 resource server
$sessionStorage = new Storage\SessionStorage();
$accessTokenStorage = new Storage\AccessTokenStorage();
@@ -30,18 +23,20 @@ $server = new ResourceServer(
);
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
// GET /tokeninfo
$router->get('/tokeninfo', function (Request $request) use ($server) {
$accessToken = $server->getAccessToken();
$session = $server->getSessionStorage()->getByAccessToken($accessToken);
$token = [
'owner_id' => $server->getOwnerId(),
'owner_type' => $server->getOwnerType(),
'access_token' => $server->getAccessToken(),
'client_id' => $server->getClientId(),
'scopes' => $server->getScopes()
'owner_id' => $session->getOwnerId(),
'owner_type' => $session->getOwnerType(),
'access_token' => $accessToken,
'client_id' => $session->getClient()->getId(),
'scopes' => $accessToken->getScopes(),
];
return new Response(json_encode($token));
@@ -58,14 +53,14 @@ $router->get('/users', function (Request $request) use ($server) {
foreach ($results as $result) {
$user = [
'username' => $result['username'],
'name' => $result['name']
'name' => $result['name'],
];
if ($server->hasScope('email')) {
if ($server->getAccessToken()->hasScope('email')) {
$user['email'] = $result['email'];
}
if ($server->hasScope('photo')) {
if ($server->getAccessToken()->hasScope('photo')) {
$user['photo'] = $result['photo'];
}
@@ -76,7 +71,7 @@ $router->get('/users', function (Request $request) use ($server) {
});
// GET /users/{username}
$router->get('/users/{username}', function (Request $request, $args) use ($server) {
$router->get('/users/{username}', function (Request $request, Response $response, array $args) use ($server) {
$result = (new Model\Users())->get($args['username']);
@@ -86,14 +81,14 @@ $router->get('/users/{username}', function (Request $request, $args) use ($serve
$user = [
'username' => $result[0]['username'],
'name' => $result[0]['name']
'name' => $result[0]['name'],
];
if ($server->hasScope('email')) {
if ($server->getAccessToken()->hasScope('email')) {
$user['email'] = $result[0]['email'];
}
if ($server->hasScope('photo')) {
if ($server->getAccessToken()->hasScope('photo')) {
$user['photo'] = $result[0]['photo'];
}
@@ -103,7 +98,6 @@ $router->get('/users/{username}', function (Request $request, $args) use ($serve
$dispatcher = $router->getDispatcher();
try {
// Check that access token is present
$server->isValidRequest(false);
@@ -112,34 +106,25 @@ try {
$request->getMethod(),
$request->getPathInfo()
);
} catch (\Orno\Http\Exception $e) {
// A failed response
$response = $e->getJsonResponse();
$response->setContent(json_encode(['status_code' => $e->getStatusCode(), 'message' => $e->getMessage()]));
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
$response = new Response(json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]), $e->httpStatusCode);
foreach ($e->getHttpHeaders() as $header) {
$response->headers($header);
}
} catch (\Exception $e) {
$response = new Orno\Http\Response;
$response = new Orno\Http\Response();
$response->setStatusCode(500);
$response->setContent(json_encode(['status_code' => 500, 'message' => $e->getMessage()]));
} finally {
// Return the response
$response->headers->set('Content-type', 'application/json');
$response->send();
}

View File

@@ -1,29 +1,24 @@
<?php
use \Orno\Http\Request;
use \Orno\Http\Response;
use \Orno\Http\JsonResponse;
use \Orno\Http\Exception\NotFoundException;
use \League\OAuth2\Server\ResourceServer;
use \RelationalExample\Storage;
use \RelationalExample\Model;
use Illuminate\Database\Capsule\Manager as Capsule;
use \League\Event\Emitter;
use Orno\Http\Request;
use Orno\Http\Response;
use RelationalExample\Storage;
include __DIR__.'/vendor/autoload.php';
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
$router->setStrategy(\Orno\Route\RouteStrategyInterface::RESTFUL_STRATEGY);
// Set up the OAuth 2.0 authorization server
$server = new \League\OAuth2\Server\AuthorizationServer;
$server->setSessionStorage(new Storage\SessionStorage);
$server->setAccessTokenStorage(new Storage\AccessTokenStorage);
$server->setRefreshTokenStorage(new Storage\RefreshTokenStorage);
$server->setClientStorage(new Storage\ClientStorage);
$server->setScopeStorage(new Storage\ScopeStorage);
$server->setAuthCodeStorage(new Storage\AuthCodeStorage);
$server = new \League\OAuth2\Server\AuthorizationServer();
$server->setSessionStorage(new Storage\SessionStorage());
$server->setAccessTokenStorage(new Storage\AccessTokenStorage());
$server->setRefreshTokenStorage(new Storage\RefreshTokenStorage());
$server->setClientStorage(new Storage\ClientStorage());
$server->setScopeStorage(new Storage\ScopeStorage());
$server->setAuthCodeStorage(new Storage\AuthCodeStorage());
$authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();
$server->addGrantType($authCodeGrant);
@@ -32,28 +27,24 @@ $refrehTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$server->addGrantType($refrehTokenGrant);
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
$router->get('/authorize', function (Request $request) use ($server) {
// First ensure the parameters in the query string are correct
try {
$authParams = $server->getGrantType('authorization_code')->checkAuthorizeParams();
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
// Normally at this point you would show the user a sign-in screen and ask them to authorize the requested scopes
@@ -78,21 +69,18 @@ $router->get('/authorize', function (Request $request) use ($server) {
$router->post('/access_token', function (Request $request) use ($server) {
try {
$response = $server->issueAccessToken();
return new Response(json_encode($response), 200);
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
});
@@ -100,40 +88,30 @@ $router->post('/access_token', function (Request $request) use ($server) {
$dispatcher = $router->getDispatcher();
try {
// A successful response
$response = $dispatcher->dispatch(
$request->getMethod(),
$request->getPathInfo()
);
} catch (\Orno\Http\Exception $e) {
// A failed response
$response = $e->getJsonResponse();
$response->setContent(json_encode(['status_code' => $e->getStatusCode(), 'message' => $e->getMessage()]));
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
$response = new Response(json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]), $e->httpStatusCode);
foreach ($e->getHttpHeaders() as $header) {
$response->headers($header);
}
} catch (\Exception $e) {
$response = new Orno\Http\Response;
$response = new Orno\Http\Response();
$response->setStatusCode(500);
$response->setContent(json_encode(['status_code' => 500, 'message' => $e->getMessage()]));
} finally {
// Return the response
$response->headers->set('Content-type', 'application/json');
$response->send();
}

View File

@@ -6,13 +6,13 @@ use Illuminate\Database\Capsule\Manager as Capsule;
include __DIR__.'/../vendor/autoload.php';
$capsule = new Capsule;
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite',
'database' => __DIR__.'/oauth2.sqlite3',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
'collation' => 'utf8_unicode_ci',
]);
$capsule->setAsGlobal();

View File

@@ -29,7 +29,7 @@ Capsule::table('users')->insert([
'password' => password_hash('whisky', PASSWORD_DEFAULT),
'name' => 'Alex Bilbie',
'email' => 'hello@alexbilbie.com',
'photo' => 'https://s.gravatar.com/avatar/14902eb1dac66b8458ebbb481d80f0a3'
'photo' => 'https://s.gravatar.com/avatar/14902eb1dac66b8458ebbb481d80f0a3',
]);
Capsule::table('users')->insert([
@@ -37,7 +37,7 @@ Capsule::table('users')->insert([
'password' => password_hash('cider', PASSWORD_DEFAULT),
'name' => 'Phil Sturgeon',
'email' => 'email@philsturgeon.co.uk',
'photo' => 'https://s.gravatar.com/avatar/14df293d6c5cd6f05996dfc606a6a951'
'photo' => 'https://s.gravatar.com/avatar/14df293d6c5cd6f05996dfc606a6a951',
]);
/******************************************************************************/
@@ -54,7 +54,7 @@ Capsule::schema()->create('oauth_clients', function ($table) {
Capsule::table('oauth_clients')->insert([
'id' => 'testclient',
'secret' => 'secret',
'name' => 'Test Client'
'name' => 'Test Client',
]);
/******************************************************************************/
@@ -69,7 +69,7 @@ Capsule::schema()->create('oauth_client_redirect_uris', function ($table) {
Capsule::table('oauth_client_redirect_uris')->insert([
'client_id' => 'testclient',
'redirect_uri' => 'http://example.com/redirect'
'redirect_uri' => 'http://example.com/redirect',
]);
/******************************************************************************/
@@ -84,17 +84,17 @@ Capsule::schema()->create('oauth_scopes', function ($table) {
Capsule::table('oauth_scopes')->insert([
'id' => 'basic',
'description' => 'Basic details about your account'
'description' => 'Basic details about your account',
]);
Capsule::table('oauth_scopes')->insert([
'id' => 'email',
'description' => 'Your email address'
'description' => 'Your email address',
]);
Capsule::table('oauth_scopes')->insert([
'id' => 'photo',
'description' => 'Your photo'
'description' => 'Your photo',
]);
/******************************************************************************/
@@ -102,7 +102,7 @@ Capsule::table('oauth_scopes')->insert([
print 'Creating sessions table'.PHP_EOL;
Capsule::schema()->create('oauth_sessions', function ($table) {
$table->increments('id');
$table->increments('id')->unsigned();
$table->string('owner_type');
$table->string('owner_id');
$table->string('client_id');
@@ -114,19 +114,19 @@ Capsule::schema()->create('oauth_sessions', function ($table) {
Capsule::table('oauth_sessions')->insert([
'owner_type' => 'client',
'owner_id' => 'testclient',
'client_id' => 'testclient'
'client_id' => 'testclient',
]);
Capsule::table('oauth_sessions')->insert([
'owner_type' => 'user',
'owner_id' => '1',
'client_id' => 'testclient'
'client_id' => 'testclient',
]);
Capsule::table('oauth_sessions')->insert([
'owner_type' => 'user',
'owner_id' => '2',
'client_id' => 'testclient'
'client_id' => 'testclient',
]);
/******************************************************************************/
@@ -135,7 +135,7 @@ print 'Creating access tokens table'.PHP_EOL;
Capsule::schema()->create('oauth_access_tokens', function ($table) {
$table->string('access_token')->primary();
$table->integer('session_id');
$table->integer('session_id')->unsigned();
$table->integer('expire_time');
$table->foreign('session_id')->references('id')->on('oauth_sessions')->onDelete('cascade');
@@ -144,19 +144,19 @@ Capsule::schema()->create('oauth_access_tokens', function ($table) {
Capsule::table('oauth_access_tokens')->insert([
'access_token' => 'iamgod',
'session_id' => '1',
'expire_time' => time() + 86400
'expire_time' => time() + 86400,
]);
Capsule::table('oauth_access_tokens')->insert([
'access_token' => 'iamalex',
'session_id' => '2',
'expire_time' => time() + 86400
'expire_time' => time() + 86400,
]);
Capsule::table('oauth_access_tokens')->insert([
'access_token' => 'iamphil',
'session_id' => '3',
'expire_time' => time() + 86400
'expire_time' => time() + 86400,
]);
/******************************************************************************/
@@ -168,7 +168,7 @@ Capsule::schema()->create('oauth_refresh_tokens', function ($table) {
$table->integer('expire_time');
$table->string('access_token');
$table->foreign('access_token')->references('id')->on('oauth_access_tokens')->onDelete('cascade');
$table->foreign('access_token')->references('access_token')->on('oauth_access_tokens')->onDelete('cascade');
});
/******************************************************************************/
@@ -177,7 +177,7 @@ print 'Creating auth codes table'.PHP_EOL;
Capsule::schema()->create('oauth_auth_codes', function ($table) {
$table->string('auth_code')->primary();
$table->integer('session_id');
$table->integer('session_id')->unsigned();
$table->integer('expire_time');
$table->string('client_redirect_uri');
@@ -189,7 +189,7 @@ Capsule::schema()->create('oauth_auth_codes', function ($table) {
print 'Creating oauth access token scopes table'.PHP_EOL;
Capsule::schema()->create('oauth_access_token_scopes', function ($table) {
$table->increments('id');
$table->increments('id')->unsigned();
$table->string('access_token');
$table->string('scope');
@@ -199,27 +199,27 @@ Capsule::schema()->create('oauth_access_token_scopes', function ($table) {
Capsule::table('oauth_access_token_scopes')->insert([
'access_token' => 'iamgod',
'scope' => 'basic'
'scope' => 'basic',
]);
Capsule::table('oauth_access_token_scopes')->insert([
'access_token' => 'iamgod',
'scope' => 'email'
'scope' => 'email',
]);
Capsule::table('oauth_access_token_scopes')->insert([
'access_token' => 'iamgod',
'scope' => 'photo'
'scope' => 'photo',
]);
Capsule::table('oauth_access_token_scopes')->insert([
'access_token' => 'iamphil',
'scope' => 'email'
'scope' => 'email',
]);
Capsule::table('oauth_access_token_scopes')->insert([
'access_token' => 'iamalex',
'scope' => 'photo'
'scope' => 'photo',
]);
/******************************************************************************/
@@ -240,8 +240,8 @@ Capsule::schema()->create('oauth_auth_code_scopes', function ($table) {
print 'Creating oauth session scopes table'.PHP_EOL;
Capsule::schema()->create('oauth_session_scopes', function ($table) {
$table->increments('id');
$table->string('session_id');
$table->increments('id')->unsigned();
$table->integer('session_id')->unsigned();
$table->string('scope');
$table->foreign('session_id')->references('id')->on('oauth_sessions')->onDelete('cascade');

View File

@@ -1,29 +1,25 @@
<?php
use \Orno\Http\Request;
use \Orno\Http\Response;
use \Orno\Http\JsonResponse;
use \Orno\Http\Exception\NotFoundException;
use \League\OAuth2\Server\ResourceServer;
use \RelationalExample\Storage;
use \RelationalExample\Model;
use Illuminate\Database\Capsule\Manager as Capsule;
use \League\Event\Emitter;
use Orno\Http\Request;
use Orno\Http\Response;
use RelationalExample\Model;
use RelationalExample\Storage;
include __DIR__.'/vendor/autoload.php';
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
$router->setStrategy(\Orno\Route\RouteStrategyInterface::RESTFUL_STRATEGY);
// Set up the OAuth 2.0 authorization server
$server = new \League\OAuth2\Server\AuthorizationServer;
$server->setSessionStorage(new Storage\SessionStorage);
$server->setAccessTokenStorage(new Storage\AccessTokenStorage);
$server->setRefreshTokenStorage(new Storage\RefreshTokenStorage);
$server->setClientStorage(new Storage\ClientStorage);
$server->setScopeStorage(new Storage\ScopeStorage);
$server->setAuthCodeStorage(new Storage\AuthCodeStorage);
$server = new \League\OAuth2\Server\AuthorizationServer();
$server->setSessionStorage(new Storage\SessionStorage());
$server->setAccessTokenStorage(new Storage\AccessTokenStorage());
$server->setRefreshTokenStorage(new Storage\RefreshTokenStorage());
$server->setClientStorage(new Storage\ClientStorage());
$server->setScopeStorage(new Storage\ScopeStorage());
$server->setAuthCodeStorage(new Storage\AuthCodeStorage());
$clientCredentials = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
$server->addGrantType($clientCredentials);
@@ -47,27 +43,24 @@ $refrehTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$server->addGrantType($refrehTokenGrant);
// Routing setup
$request = (new Request)->createFromGlobals();
$router = new \Orno\Route\RouteCollection;
$request = (new Request())->createFromGlobals();
$router = new \Orno\Route\RouteCollection();
$router->post('/access_token', function (Request $request) use ($server) {
try {
$response = $server->issueAccessToken();
return new Response(json_encode($response), 200);
} catch (\Exception $e) {
return new Response(
json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]),
$e->httpStatusCode,
$e->getHttpHeaders()
);
}
});
@@ -75,40 +68,30 @@ $router->post('/access_token', function (Request $request) use ($server) {
$dispatcher = $router->getDispatcher();
try {
// A successful response
$response = $dispatcher->dispatch(
$request->getMethod(),
$request->getPathInfo()
);
} catch (\Orno\Http\Exception $e) {
// A failed response
$response = $e->getJsonResponse();
$response->setContent(json_encode(['status_code' => $e->getStatusCode(), 'message' => $e->getMessage()]));
} catch (\League\OAuth2\Server\Exception\OAuthException $e) {
$response = new Response(json_encode([
'error' => $e->errorType,
'message' => $e->getMessage()
'message' => $e->getMessage(),
]), $e->httpStatusCode);
foreach ($e->getHttpHeaders() as $header) {
$response->headers($header);
}
} catch (\Exception $e) {
$response = new Orno\Http\Response;
$response = new Orno\Http\Response();
$response->setStatusCode(500);
$response->setContent(json_encode(['status_code' => 500, 'message' => $e->getMessage()]));
} finally {
// Return the response
$response->headers->set('Content-type', 'application/json');
$response->send();
}

View File

@@ -11,21 +11,20 @@
namespace League\OAuth2\Server;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\TokenType\TokenTypeInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use Symfony\Component\HttpFoundation\Request;
use League\Event\Emitter;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\MacTokenInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\TokenType\TokenTypeInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* OAuth 2.0 Resource Server
*/
abstract class AbstractServer
{
/**
@@ -37,48 +36,61 @@ abstract class AbstractServer
/**
* Session storage
*
* @var \League\OAuth2\Server\Storage\SessionInterface
*/
protected $sessionStorage;
/**
* Access token storage
*
* @var \League\OAuth2\Server\Storage\AccessTokenInterface
*/
protected $accessTokenStorage;
/**
* Refresh token storage
*
* @var \League\OAuth2\Server\Storage\RefreshTokenInterface
*/
protected $refreshTokenStorage;
/**
* Auth code storage
*
* @var \League\OAuth2\Server\Storage\AuthCodeInterface
*/
protected $authCodeStorage;
/**
* Scope storage
*
* @var \League\OAuth2\Server\Storage\ScopeInterface
*/
protected $scopeStorage;
/**
* Client storage
*
* @var \League\OAuth2\Server\Storage\ClientInterface
*/
protected $clientStorage;
/**
* @var \League\OAuth2\Server\Storage\MacTokenInterface
*/
protected $macStorage;
/**
* Token type
*
* @var \League\OAuth2\Server\TokenType\TokenTypeInterface
*/
protected $tokenType;
/**
* Event emitter
*
* @var \League\Event\Emitter
*/
protected $eventEmitter;
@@ -93,12 +105,13 @@ abstract class AbstractServer
/**
* Set an event emitter
*
* @param object $emitter Event emitter object
*/
public function setEventEmitter($emitter = null)
{
if ($emitter === null) {
$this->eventEmitter = new Emitter;
$this->eventEmitter = new Emitter();
} else {
$this->eventEmitter = $emitter;
}
@@ -106,16 +119,19 @@ abstract class AbstractServer
/**
* Add an event listener to the event emitter
*
* @param string $eventName Event name
* @param callable $listener Callable function or method
* @param int $priority Priority of event listener
*/
public function addEventListener($eventName, callable $listener)
public function addEventListener($eventName, callable $listener, $priority = Emitter::P_NORMAL)
{
$this->eventEmitter->addListener($eventName, $listener);
$this->eventEmitter->addListener($eventName, $listener, $priority);
}
/**
* Returns the event emitter
*
* @return \League\Event\Emitter
*/
public function getEventEmitter()
@@ -125,7 +141,9 @@ abstract class AbstractServer
/**
* Sets the Request Object
*
* @param \Symfony\Component\HttpFoundation\Request The Request Object
*
* @return self
*/
public function setRequest($request)
@@ -137,6 +155,7 @@ abstract class AbstractServer
/**
* Gets the Request object. It will create one from the globals if one is not set.
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
@@ -150,7 +169,9 @@ abstract class AbstractServer
/**
* Set the client storage
* @param \League\OAuth2\Server\Storage\ClientInterface $storage
*
* @param \League\OAuth2\Server\Storage\ClientInterface $storage
*
* @return self
*/
public function setClientStorage(ClientInterface $storage)
@@ -163,7 +184,9 @@ abstract class AbstractServer
/**
* Set the session storage
* @param \League\OAuth2\Server\Storage\SessionInterface $storage
*
* @param \League\OAuth2\Server\Storage\SessionInterface $storage
*
* @return self
*/
public function setSessionStorage(SessionInterface $storage)
@@ -176,7 +199,9 @@ abstract class AbstractServer
/**
* Set the access token storage
* @param \League\OAuth2\Server\Storage\AccessTokenInterface $storage
*
* @param \League\OAuth2\Server\Storage\AccessTokenInterface $storage
*
* @return self
*/
public function setAccessTokenStorage(AccessTokenInterface $storage)
@@ -189,7 +214,9 @@ abstract class AbstractServer
/**
* Set the refresh token storage
* @param \League\OAuth2\Server\Storage\RefreshTokenInteface $storage
*
* @param \League\OAuth2\Server\Storage\RefreshTokenInterface $storage
*
* @return self
*/
public function setRefreshTokenStorage(RefreshTokenInterface $storage)
@@ -202,7 +229,9 @@ abstract class AbstractServer
/**
* Set the auth code storage
* @param \League\OAuth2\Server\Storage\AuthCodeInterface $authCode
*
* @param \League\OAuth2\Server\Storage\AuthCodeInterface $storage
*
* @return self
*/
public function setAuthCodeStorage(AuthCodeInterface $storage)
@@ -215,7 +244,9 @@ abstract class AbstractServer
/**
* Set the scope storage
* @param \League\OAuth2\Server\Storage\ScopeInterface $storage
*
* @param \League\OAuth2\Server\Storage\ScopeInterface $storage
*
* @return self
*/
public function setScopeStorage(ScopeInterface $storage)
@@ -228,6 +259,7 @@ abstract class AbstractServer
/**
* Return the client storage
*
* @return \League\OAuth2\Server\Storage\ClientInterface
*/
public function getClientStorage()
@@ -237,6 +269,7 @@ abstract class AbstractServer
/**
* Return the scope storage
*
* @return \League\OAuth2\Server\Storage\ScopeInterface
*/
public function getScopeStorage()
@@ -246,6 +279,7 @@ abstract class AbstractServer
/**
* Return the session storage
*
* @return \League\OAuth2\Server\Storage\SessionInterface
*/
public function getSessionStorage()
@@ -255,6 +289,7 @@ abstract class AbstractServer
/**
* Return the refresh token storage
*
* @return \League\OAuth2\Server\Storage\RefreshTokenInterface
*/
public function getRefreshTokenStorage()
@@ -264,6 +299,7 @@ abstract class AbstractServer
/**
* Return the access token storage
*
* @return \League\OAuth2\Server\Storage\AccessTokenInterface
*/
public function getAccessTokenStorage()
@@ -273,6 +309,7 @@ abstract class AbstractServer
/**
* Return the auth code storage
*
* @return \League\OAuth2\Server\Storage\AuthCodeInterface
*/
public function getAuthCodeStorage()
@@ -282,7 +319,9 @@ abstract class AbstractServer
/**
* Set the access token type
* @param TokenTypeInterface $tokenType The token type
*
* @param TokenTypeInterface $tokenType The token type
*
* @return void
*/
public function setTokenType(TokenTypeInterface $tokenType)
@@ -293,10 +332,27 @@ abstract class AbstractServer
/**
* Get the access token type
*
* @return TokenTypeInterface
*/
public function getTokenType()
{
return $this->tokenType;
}
/**
* @return MacTokenInterface
*/
public function getMacStorage()
{
return $this->macStorage;
}
/**
* @param MacTokenInterface $macStorage
*/
public function setMacStorage(MacTokenInterface $macStorage)
{
$this->macStorage = $macStorage;
}
}

View File

@@ -12,14 +12,7 @@
namespace League\OAuth2\Server;
use League\OAuth2\Server\Grant\GrantTypeInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\AuthCodeInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\TokenType\Bearer;
use Symfony\Component\HttpFoundation\Request;
/**
* OAuth 2.0 authorization server class
@@ -27,56 +20,64 @@ use Symfony\Component\HttpFoundation\Request;
class AuthorizationServer extends AbstractServer
{
/**
* The delimeter between scopes specified in the scope query string parameter
* The delimiter between scopes specified in the scope query string parameter
* The OAuth 2 specification states it should be a space but most use a comma
*
* @var string
*/
protected $scopeDelimeter = ' ';
protected $scopeDelimiter = ' ';
/**
* The TTL (time to live) of an access token in seconds (default: 3600)
*
* @var integer
*/
protected $accessTokenTTL = 3600;
/**
* The registered grant response types
*
* @var array
*/
protected $responseTypes = [];
/**
* The registered grant types
*
* @var array
*/
protected $grantTypes = [];
/**
* Require the "scope" parameter to be in checkAuthoriseParams()
*
* @var boolean
*/
protected $requireScopeParam = false;
/**
* Default scope(s) to be used if none is provided
*
* @var string|array
*/
protected $defaultScope;
/**
* Require the "state" parameter to be in checkAuthoriseParams()
*
* @var boolean
*/
protected $requireStateParam = false;
/**
* Create a new OAuth2 authorization server
*
* @return self
*/
public function __construct()
{
// Set Bearer as the default token type
$this->setTokenType(new Bearer);
$this->setTokenType(new Bearer());
parent::__construct();
@@ -85,8 +86,10 @@ class AuthorizationServer extends AbstractServer
/**
* Enable support for a grant
* @param GrantTypeInterface $grantType A grant class which conforms to Interface/GrantTypeInterface
* @param null|string $identifier An identifier for the grant (autodetected if not passed)
*
* @param GrantTypeInterface $grantType A grant class which conforms to Interface/GrantTypeInterface
* @param null|string $identifier An identifier for the grant (autodetected if not passed)
*
* @return self
*/
public function addGrantType(GrantTypeInterface $grantType, $identifier = null)
@@ -109,7 +112,9 @@ class AuthorizationServer extends AbstractServer
/**
* Check if a grant type has been enabled
* @param string $identifier The grant type identifier
*
* @param string $identifier The grant type identifier
*
* @return boolean Returns "true" if enabled, "false" if not
*/
public function hasGrantType($identifier)
@@ -119,6 +124,7 @@ class AuthorizationServer extends AbstractServer
/**
* Returns response types
*
* @return array
*/
public function getResponseTypes()
@@ -127,8 +133,10 @@ class AuthorizationServer extends AbstractServer
}
/**
* Require the "scope" paremter in checkAuthoriseParams()
* @param boolean $require
* Require the "scope" parameter in checkAuthoriseParams()
*
* @param boolean $require
*
* @return self
*/
public function requireScopeParam($require = true)
@@ -140,6 +148,7 @@ class AuthorizationServer extends AbstractServer
/**
* Is the scope parameter required?
*
* @return bool
*/
public function scopeParamRequired()
@@ -149,8 +158,10 @@ class AuthorizationServer extends AbstractServer
/**
* Default scope to be used if none is provided and requireScopeParam() is false
*
* @param string $default Name of the default scope
* @param self
*
* @return self
*/
public function setDefaultScope($default = null)
{
@@ -161,6 +172,7 @@ class AuthorizationServer extends AbstractServer
/**
* Default scope to be used if none is provided and requireScopeParam is false
*
* @return string|null
*/
public function getDefaultScope()
@@ -169,9 +181,9 @@ class AuthorizationServer extends AbstractServer
}
/**
* Require the "state" paremter in checkAuthoriseParams()
* @param boolean $require
* @return void
* Require the "state" parameter in checkAuthoriseParams()
*
* @return bool
*/
public function stateParamRequired()
{
@@ -179,9 +191,11 @@ class AuthorizationServer extends AbstractServer
}
/**
* Require the "state" paremter in checkAuthoriseParams()
* @param boolean $require
* @return void
* Require the "state" parameter in checkAuthoriseParams()
*
* @param boolean $require
*
* @return self
*/
public function requireStateParam($require = true)
{
@@ -191,27 +205,32 @@ class AuthorizationServer extends AbstractServer
}
/**
* Get the scope delimeter
* Get the scope delimiter
*
* @return string The scope delimiter (default: ",")
*/
public function getScopeDelimeter()
public function getScopeDelimiter()
{
return $this->scopeDelimeter;
return $this->scopeDelimiter;
}
/**
* Set the scope delimiter
* @param string $scopeDelimeter
*
* @param string $scopeDelimiter
*
* @return self
*/
public function setScopeDelimeter($scopeDelimeter = ' ')
public function setScopeDelimiter($scopeDelimiter = ' ')
{
$this->scopeDelimeter = $scopeDelimeter;
$this->scopeDelimiter = $scopeDelimiter;
return $this;
}
/**
* Get the TTL for an access token
*
* @return int The TTL
*/
public function getAccessTokenTTL()
@@ -221,7 +240,10 @@ class AuthorizationServer extends AbstractServer
/**
* Set the TTL for an access token
*
* @param int $accessTokenTTL The new TTL
*
* @return self
*/
public function setAccessTokenTTL($accessTokenTTL = 3600)
{
@@ -232,7 +254,10 @@ class AuthorizationServer extends AbstractServer
/**
* Issue an access token
*
* @return array Authorise request parameters
*
* @throws
*/
public function issueAccessToken()
{
@@ -252,8 +277,12 @@ class AuthorizationServer extends AbstractServer
/**
* Return a grant type class
* @param string $grantType The grant type identifer
*
* @param string $grantType The grant type identifier
*
* @return Grant\GrantTypeInterface
*
* @throws
*/
public function getGrantType($grantType)
{

View File

@@ -11,10 +11,8 @@
namespace League\OAuth2\Server\Entity;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\AbstractServer;
use Symfony\Component\HttpFoundation\ParameterBag;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Util\SecureKey;
/**
* Abstract token class
@@ -23,37 +21,44 @@ abstract class AbstractTokenEntity
{
/**
* Token identifier
*
* @var string
*/
protected $id;
/**
* Associated session
*
* @var \League\OAuth2\Server\Entity\SessionEntity
*/
protected $session;
/**
* Session scopes
*
* @var \League\OAuth2\Server\Entity\ScopeEntity[]
*/
protected $scopes;
/**
* Token expire time
*
* @var int
*/
protected $expireTime = 0;
/**
* Authorization or resource server
*
* @var \League\OAuth2\Server\AbstractServer
*/
protected $server;
/**
* __construct
* @param \League\OAuth2\Server\AbstractServer $server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function __construct(AbstractServer $server)
@@ -65,7 +70,9 @@ abstract class AbstractTokenEntity
/**
* Set session
* @param \League\OAuth2\Server\Entity\SessionEntity $session
*
* @param \League\OAuth2\Server\Entity\SessionEntity $session
*
* @return self
*/
public function setSession(SessionEntity $session)
@@ -77,7 +84,9 @@ abstract class AbstractTokenEntity
/**
* Set the expire time of the token
* @param integer $expireTime Unix time stamp
*
* @param integer $expireTime Unix time stamp
*
* @return self
*/
public function setExpireTime($expireTime)
@@ -89,6 +98,7 @@ abstract class AbstractTokenEntity
/**
* Return token expire time
*
* @return int
*/
public function getExpireTime()
@@ -98,6 +108,7 @@ abstract class AbstractTokenEntity
/**
* Is the token expired?
*
* @return bool
*/
public function isExpired()
@@ -107,7 +118,9 @@ abstract class AbstractTokenEntity
/**
* Set token ID
* @param string $token Token ID
*
* @param string $id Token ID
*
* @return self
*/
public function setId($id = null)
@@ -119,6 +132,7 @@ abstract class AbstractTokenEntity
/**
* Get the token ID
*
* @return string
*/
public function getId()
@@ -128,7 +142,9 @@ abstract class AbstractTokenEntity
/**
* Associate a scope
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope
*
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope
*
* @return self
*/
public function associateScope(ScopeEntity $scope)
@@ -142,7 +158,9 @@ abstract class AbstractTokenEntity
/**
* Format the local scopes array
*
* @param \League\OAuth2\Server\Entity\ScopeEntity[]
*
* @return array
*/
protected function formatScopes($unformatted = [])
@@ -163,6 +181,7 @@ abstract class AbstractTokenEntity
/**
* Returns the token as a string if the object is cast as a string
*
* @return string
*/
public function __toString()
@@ -170,17 +189,20 @@ abstract class AbstractTokenEntity
if ($this->id === null) {
return '';
}
return $this->id;
}
/**
* Expire the token
*
* @return void
*/
abstract public function expire();
/**
* Save the token
*
* @return void
*/
abstract public function save();

View File

@@ -18,6 +18,7 @@ class AccessTokenEntity extends AbstractTokenEntity
{
/**
* Get session
*
* @return \League\OAuth2\Server\Entity\SessionEntity
*/
public function getSession()
@@ -33,7 +34,9 @@ class AccessTokenEntity extends AbstractTokenEntity
/**
* Check if access token has an associated scope
* @param string $scope Scope to check
*
* @param string $scope Scope to check
*
* @return bool
*/
public function hasScope($scope)
@@ -47,7 +50,8 @@ class AccessTokenEntity extends AbstractTokenEntity
/**
* Return all scopes associated with the access token
* @return \League\OAuth2\Server\Entity\Scope[]
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function getScopes()
{

View File

@@ -12,19 +12,22 @@
namespace League\OAuth2\Server\Entity;
/**
* Access token entity class
* Auth Code entity class
*/
class AuthCodeEntity extends AbstractTokenEntity
{
/**
* Redirect URI
*
* @var string
*/
protected $redirectUri = '';
/**
* Set the redirect URI for the authorization request
* @param string $redirectUri
*
* @param string $redirectUri
*
* @return self
*/
public function setRedirectUri($redirectUri)
@@ -36,6 +39,7 @@ class AuthCodeEntity extends AbstractTokenEntity
/**
* Get the redirect URI
*
* @return string
*/
public function getRedirectUri()
@@ -45,8 +49,10 @@ class AuthCodeEntity extends AbstractTokenEntity
/**
* Generate a redirect URI
* @param string $state The state parameter if set by the client
* @param string $queryDelimeter The query delimiter ('?' for auth code grant, '#' for implicit grant)
*
* @param string $state The state parameter if set by the client
* @param string $queryDelimeter The query delimiter ('?' for auth code grant, '#' for implicit grant)
*
* @return string
*/
public function generateRedirectUri($state = null, $queryDelimeter = '?')
@@ -56,12 +62,13 @@ class AuthCodeEntity extends AbstractTokenEntity
return $uri.http_build_query([
'code' => $this->getId(),
'state' => $state
'state' => $state,
]);
}
/**
* Get session
*
* @return \League\OAuth2\Server\Entity\SessionEntity
*/
public function getSession()
@@ -77,7 +84,8 @@ class AuthCodeEntity extends AbstractTokenEntity
/**
* Return all scopes associated with the session
* @return \League\OAuth2\Server\Entity\Scope[]
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function getScopes()
{

View File

@@ -22,37 +22,44 @@ class ClientEntity
/**
* Client identifier
*
* @var string
*/
protected $id = null;
/**
* Client secret
*
* @var string
*/
protected $secret = null;
/**
* Client name
*
* @var string
*/
protected $name = null;
/**
* Client redirect URI
*
* @var string
*/
protected $redirectUri = null;
/**
* Authorization or resource server
*
* @var \League\OAuth2\Server\AbstractServer
*/
protected $server;
/**
* __construct
* @param \League\OAuth2\Server\AbstractServer $server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function __construct(AbstractServer $server)
@@ -64,6 +71,7 @@ class ClientEntity
/**
* Return the client identifier
*
* @return string
*/
public function getId()
@@ -73,6 +81,7 @@ class ClientEntity
/**
* Return the client secret
*
* @return string
*/
public function getSecret()
@@ -82,6 +91,7 @@ class ClientEntity
/**
* Get the client name
*
* @return string
*/
public function getName()
@@ -91,6 +101,7 @@ class ClientEntity
/**
* Returnt the client redirect URI
*
* @return string
*/
public function getRedirectUri()

View File

@@ -15,7 +15,10 @@ trait EntityTrait
{
/**
* Hydrate an entity with properites
* @param array $properties
*
* @param array $properties
*
* @return self
*/
public function hydrate(array $properties)
{

View File

@@ -18,19 +18,23 @@ class RefreshTokenEntity extends AbstractTokenEntity
{
/**
* Access token associated to refresh token
*
* @var \League\OAuth2\Server\Entity\AccessTokenEntity
*/
protected $accessTokenEntity;
/**
* Id of the access token
*
* @var string
*/
protected $accessTokenId;
/**
* Set the ID of the associated access token
* @param string $accessToken
*
* @param string $accessTokenId
*
* @return self
*/
public function setAccessTokenId($accessTokenId)
@@ -42,7 +46,9 @@ class RefreshTokenEntity extends AbstractTokenEntity
/**
* Associate an access token
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessTokenEntity
*
* @return self
*/
public function setAccessToken(AccessTokenEntity $accessTokenEntity)
@@ -54,7 +60,8 @@ class RefreshTokenEntity extends AbstractTokenEntity
/**
* Return access token
* @return AccessToken
*
* @return AccessTokenEntity
*/
public function getAccessToken()
{

View File

@@ -22,25 +22,30 @@ class ScopeEntity implements \JsonSerializable
/**
* Scope identifier
*
* @var string
*/
protected $id;
/**
* Scope description
*
* @var string
*/
protected $description;
/**
* Authorization or resource server
*
* @var \League\OAuth2\Server\AbstractServer
*/
protected $server;
/**
* __construct
* @param \League\OAuth2\Server\AbstractServer $server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function __construct(AbstractServer $server)
@@ -52,6 +57,7 @@ class ScopeEntity implements \JsonSerializable
/**
* Return the scope identifer
*
* @return string
*/
public function getId()
@@ -61,6 +67,7 @@ class ScopeEntity implements \JsonSerializable
/**
* Return the scope's description
*
* @return string
*/
public function getDescription()
@@ -70,6 +77,7 @@ class ScopeEntity implements \JsonSerializable
/**
* Returns a JSON object when entity is passed into json_encode
*
* @return array
*/
public function jsonSerialize()

View File

@@ -12,8 +12,7 @@
namespace League\OAuth2\Server\Entity;
use League\OAuth2\Server\AbstractServer;
use League\OAuth2\Server\Event;
use Symfony\Component\HttpFoundation\ParameterBag;
use League\OAuth2\Server\Event\SessionOwnerEvent;
/**
* Session entity grant
@@ -22,61 +21,72 @@ class SessionEntity
{
/**
* Session identifier
*
* @var string
*/
protected $id;
/**
* Client identifier
*
* @var \League\OAuth2\Server\Entity\ClientEntity
*/
protected $client;
/**
* Session owner identifier
*
* @var string
*/
protected $ownerId;
/**
* Session owner type (e.g. "user")
*
* @var string
*/
protected $ownerType;
/**
* Auth code
*
* @var \League\OAuth2\Server\Entity\AuthCodeEntity
*/
protected $authCode;
/**
* Access token
*
* @var \League\OAuth2\Server\Entity\AccessTokenEntity
*/
protected $accessToken;
/**
* Refresh token
*
* @var \League\OAuth2\Server\Entity\RefreshTokenEntity
*/
protected $refreshToken;
/**
* Session scopes
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*/
protected $scopes;
/**
* Authorization or resource server
*
* @var \League\OAuth2\Server\AuthorizationServer|\League\OAuth2\Server\ResourceServer
*/
protected $server;
/**
* __construct
* @param \League\OAuth2\Server\AbstractServer $server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function __construct(AbstractServer $server)
@@ -88,7 +98,9 @@ class SessionEntity
/**
* Set the session identifier
* @param string $id
*
* @param string $id
*
* @return self
*/
public function setId($id)
@@ -100,6 +112,7 @@ class SessionEntity
/**
* Return the session identifier
*
* @return string
*/
public function getId()
@@ -109,7 +122,9 @@ class SessionEntity
/**
* Associate a scope
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope
*
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope
*
* @return self
*/
public function associateScope(ScopeEntity $scope)
@@ -123,7 +138,9 @@ class SessionEntity
/**
* Check if access token has an associated scope
* @param string $scope Scope to check
*
* @param string $scope Scope to check
*
* @return bool
*/
public function hasScope($scope)
@@ -137,7 +154,8 @@ class SessionEntity
/**
* Return all scopes associated with the session
* @return \League\OAuth2\Server\Entity\Scope[]
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function getScopes()
{
@@ -150,14 +168,16 @@ class SessionEntity
/**
* Format the local scopes array
*
* @param \League\OAuth2\Server\Entity\Scope[]
*
* @return array
*/
private function formatScopes($unformated = [])
private function formatScopes($unformatted = [])
{
$scopes = [];
if (is_array($unformated)) {
foreach ($unformated as $scope) {
if (is_array($unformatted)) {
foreach ($unformatted as $scope) {
if ($scope instanceof ScopeEntity) {
$scopes[$scope->getId()] = $scope;
}
@@ -169,7 +189,9 @@ class SessionEntity
/**
* Associate an access token with the session
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken
*
* @return self
*/
public function associateAccessToken(AccessTokenEntity $accessToken)
@@ -181,7 +203,9 @@ class SessionEntity
/**
* Associate a refresh token with the session
* @param \League\OAuth2\Server\Entity\RefreshTokenEntity $refreshToken
*
* @param \League\OAuth2\Server\Entity\RefreshTokenEntity $refreshToken
*
* @return self
*/
public function associateRefreshToken(RefreshTokenEntity $refreshToken)
@@ -193,7 +217,9 @@ class SessionEntity
/**
* Associate a client with the session
* @param \League\OAuth2\Server\Entity\ClientEntity $client The client
*
* @param \League\OAuth2\Server\Entity\ClientEntity $client The client
*
* @return self
*/
public function associateClient(ClientEntity $client)
@@ -205,6 +231,7 @@ class SessionEntity
/**
* Return the session client
*
* @return \League\OAuth2\Server\Entity\ClientEntity
*/
public function getClient()
@@ -220,8 +247,10 @@ class SessionEntity
/**
* Set the session owner
* @param string $type The type of the owner (e.g. user, app)
* @param string $id The identifier of the owner
*
* @param string $type The type of the owner (e.g. user, app)
* @param string $id The identifier of the owner
*
* @return self
*/
public function setOwner($type, $id)
@@ -229,13 +258,14 @@ class SessionEntity
$this->ownerType = $type;
$this->ownerId = $id;
$this->server->getEventEmitter()->emit(new Event\SessionOwnerEvent($this));
$this->server->getEventEmitter()->emit(new SessionOwnerEvent($this));
return $this;
}
/**
* Return session owner identifier
*
* @return string
*/
public function getOwnerId()
@@ -245,6 +275,7 @@ class SessionEntity
/**
* Return session owner type
*
* @return string
*/
public function getOwnerType()
@@ -254,6 +285,7 @@ class SessionEntity
/**
* Save the session
*
* @return void
*/
public function save()

View File

@@ -18,13 +18,15 @@ class ClientAuthenticationFailedEvent extends AbstractEvent
{
/**
* Request
*
* @var \Symfony\Component\HttpFoundation\Request
*/
private $request;
/**
* Init the event with a request
* @param \Symfony\Component\HttpFoundation\Requesty $request
*
* @param \Symfony\Component\HttpFoundation\Request $request
*/
public function __construct(Request $request)
{
@@ -33,6 +35,7 @@ class ClientAuthenticationFailedEvent extends AbstractEvent
/**
* The name of the event
*
* @return string
*/
public function getName()
@@ -42,6 +45,7 @@ class ClientAuthenticationFailedEvent extends AbstractEvent
/**
* Return request
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()

View File

@@ -18,12 +18,14 @@ class SessionOwnerEvent extends AbstractEvent
{
/**
* Session entity
*
* @var \League\OAuth2\Server\Entity\SessionEntity
*/
private $session;
/**
* Init the event with a session
*
* @param \League\OAuth2\Server\Entity\SessionEntity $session
*/
public function __construct(SessionEntity $session)
@@ -33,6 +35,7 @@ class SessionOwnerEvent extends AbstractEvent
/**
* The name of the event
*
* @return string
*/
public function getName()
@@ -42,6 +45,7 @@ class SessionOwnerEvent extends AbstractEvent
/**
* Return session
*
* @return \League\OAuth2\Server\Entity\SessionEntity
*/
public function getSession()

View File

@@ -18,13 +18,15 @@ class UserAuthenticationFailedEvent extends AbstractEvent
{
/**
* Request
*
* @var \Symfony\Component\HttpFoundation\Request
*/
private $request;
/**
* Init the event with a request
* @param \Symfony\Component\HttpFoundation\Requesty $request
*
* @param \Symfony\Component\HttpFoundation\Request $request
*/
public function __construct(Request $request)
{
@@ -33,6 +35,7 @@ class UserAuthenticationFailedEvent extends AbstractEvent
/**
* The name of the event
*
* @return string
*/
public function getName()
@@ -42,6 +45,7 @@ class UserAuthenticationFailedEvent extends AbstractEvent
/**
* Return request
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()

View File

@@ -32,6 +32,7 @@ class InvalidGrantException extends OAuthException
public function __construct($parameter)
{
$this->parameter = $parameter;
parent::__construct(
sprintf(
'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. Check the "%s" parameter.',

View File

@@ -32,6 +32,7 @@ class InvalidRequestException extends OAuthException
public function __construct($parameter, $redirectUri = null)
{
$this->parameter = $parameter;
parent::__construct(
sprintf(
'The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the "%s" parameter.',

View File

@@ -32,6 +32,7 @@ class InvalidScopeException extends OAuthException
public function __construct($parameter, $redirectUri = null)
{
$this->parameter = $parameter;
parent::__construct(
sprintf(
'The requested scope is invalid, unknown, or malformed. Check the "%s" scope.',

View File

@@ -11,6 +11,7 @@
namespace League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\RedirectUri;
use Symfony\Component\HttpFoundation\Request;
/**
@@ -25,6 +26,7 @@ class OAuthException extends \Exception
/**
* Redirect URI if the server should redirect back to the client
*
* @var string|null
*/
public $redirectUri = null;
@@ -34,8 +36,15 @@ class OAuthException extends \Exception
*/
public $errorType = '';
/**
* Parameter eventually passed to Exception
*/
public $parameter = '';
/**
* Throw a new exception
*
* @param string $msg Exception Message
*/
public function __construct($msg = 'An error occured')
{
@@ -44,6 +53,7 @@ class OAuthException extends \Exception
/**
* Should the server redirect back to the client?
*
* @return bool
*/
public function shouldRedirect()
@@ -53,11 +63,12 @@ class OAuthException extends \Exception
/**
* Return redirect URI if set
*
* @return string|null
*/
public function getRedirectUri()
{
return \League\OAuth2\Server\Util\RedirectUri::make(
return RedirectUri::make(
$this->redirectUri,
[
'error' => $this->errorType,
@@ -66,8 +77,19 @@ class OAuthException extends \Exception
);
}
/**
* Return parameter if set
*
* @return string
*/
public function getParameter()
{
return $this->parameter;
}
/**
* Get all headers that have to be send with the error response
*
* @return array Array with header values
*/
public function getHttpHeaders()

View File

@@ -31,7 +31,9 @@ class ServerErrorException extends OAuthException
*/
public function __construct($parameter = null)
{
$this->parameter = $parameter;
$parameter = is_null($parameter) ? 'The authorization server encountered an unexpected condition which prevented it from fulfilling the request.' : $parameter;
parent::__construct($parameter);
}
}

View File

@@ -32,6 +32,7 @@ class UnsupportedGrantTypeException extends OAuthException
public function __construct($parameter)
{
$this->parameter = $parameter;
parent::__construct(
sprintf(
'The authorization grant type "%s" is not supported by the authorization server.',

View File

@@ -31,6 +31,7 @@ class UnsupportedResponseTypeException extends OAuthException
*/
public function __construct($parameter, $redirectUri = null)
{
$this->parameter = $parameter;
parent::__construct('The authorization server does not support obtaining an access token using this method.');
$this->redirectUri = $redirectUri;
}

View File

@@ -12,8 +12,8 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Exception;
/**
@@ -23,37 +23,41 @@ abstract class AbstractGrant implements GrantTypeInterface
{
/**
* Grant identifier
*
* @var string
*/
protected $identifier = '';
/**
* Response type
*
* @var string
*/
protected $responseType;
/**
* Callback to authenticate a user's name and password
* @var function
*
* @var callable
*/
protected $callback;
/**
* AuthServer instance
*
* @var \League\OAuth2\Server\AuthorizationServer
*/
protected $server;
/**
* Access token expires in override
*
* @var int
*/
protected $accessTokenTTL;
/**
* Return the identifier
* @return string
* {@inheritdoc}
*/
public function getIdentifier()
{
@@ -61,9 +65,7 @@ abstract class AbstractGrant implements GrantTypeInterface
}
/**
* Return the identifier
* @param string $identifier
* @return self
* {@inheritdoc}
*/
public function setIdentifier($identifier)
{
@@ -73,8 +75,7 @@ abstract class AbstractGrant implements GrantTypeInterface
}
/**
* Return the response type
* @return string
* {@inheritdoc}
*/
public function getResponseType()
{
@@ -83,6 +84,7 @@ abstract class AbstractGrant implements GrantTypeInterface
/**
* Get the TTL for an access token
*
* @return int The TTL
*/
public function getAccessTokenTTL()
@@ -96,7 +98,9 @@ abstract class AbstractGrant implements GrantTypeInterface
/**
* Override the default access token expire time
* @param int $accessTokenTTL
*
* @param int $accessTokenTTL
*
* @return self
*/
public function setAccessTokenTTL($accessTokenTTL)
@@ -107,9 +111,7 @@ abstract class AbstractGrant implements GrantTypeInterface
}
/**
* Inject the authorization server into the grant
* @param \League\OAuth2\Server\AuthorizationServer $server The authorization server instance
* @return self
* {@inheritdoc}
*/
public function setAuthorizationServer(AuthorizationServer $server)
{
@@ -120,15 +122,19 @@ abstract class AbstractGrant implements GrantTypeInterface
/**
* Given a list of scopes, validate them and return an array of Scope entities
* @param string $scopeParam A string of scopes (e.g. "profile email birthday")
* @param \League\OAuth2\Server\Entity\ClientEntity $client Client entity
* @param string|null $redirectUri The redirect URI to return the user to
*
* @param string $scopeParam A string of scopes (e.g. "profile email birthday")
* @param \League\OAuth2\Server\Entity\ClientEntity $client Client entity
* @param string|null $redirectUri The redirect URI to return the user to
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
* @throws \League\OAuth2\Server\Exception\InvalidScopeException If scope is invalid, or no scopes passed when required
*
* @throws \League\OAuth2\Server\Exception\InvalidScopeException If scope is invalid, or no scopes passed when required
* @throws
*/
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null)
{
$scopesList = explode($this->server->getScopeDelimeter(), $scopeParam);
$scopesList = explode($this->server->getScopeDelimiter(), $scopeParam);
for ($i = 0; $i < count($scopesList); $i++) {
$scopesList[$i] = trim($scopesList[$i]);
@@ -172,7 +178,9 @@ abstract class AbstractGrant implements GrantTypeInterface
/**
* Format the local scopes array
*
* @param \League\OAuth2\Server\Entity\ScopeEntity[]
*
* @return array
*/
protected function formatScopes($unformated = [])

View File

@@ -11,15 +11,14 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Event;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
/**
* Auth code grant class
@@ -28,37 +27,52 @@ class AuthCodeGrant extends AbstractGrant
{
/**
* Grant identifier
*
* @var string
*/
protected $identifier = 'authorization_code';
/**
* Response type
*
* @var string
*/
protected $responseType = 'code';
/**
* AuthServer instance
* @var AuthServer
*
* @var \League\OAuth2\Server\AuthorizationServer
*/
protected $server = null;
/**
* Access token expires in override
*
* @var int
*/
protected $accessTokenTTL = null;
/**
* The TTL of the auth token
*
* @var integer
*/
protected $authTokenTTL = 600;
/**
* Whether to require the client secret when
* completing the flow.
*
* @var boolean
*/
protected $requireClientSecret = true;
/**
* Override the default access token expire time
* @param int $authTokenTTL
*
* @param int $authTokenTTL
*
* @return void
*/
public function setAuthTokenTTL($authTokenTTL)
@@ -66,10 +80,33 @@ class AuthCodeGrant extends AbstractGrant
$this->authTokenTTL = $authTokenTTL;
}
/**
*
* @param bool $required True to require client secret during access
* token request. False if not. Default = true
*/
public function setRequireClientSecret($required)
{
$this->requireClientSecret = $required;
}
/**
* True if client secret is required during
* access token request. False if it isn't.
*
* @return bool
*/
public function shouldRequireClientSecret()
{
return $this->requireClientSecret;
}
/**
* Check authorize parameters
*
* @return array Authorize request parameters
*
* @throws
*/
public function checkAuthorizeParams()
{
@@ -117,20 +154,21 @@ class AuthCodeGrant extends AbstractGrant
$scopes = $this->validateScopes($scopeParam, $client, $redirectUri);
return [
'client' => $client,
'redirect_uri' => $redirectUri,
'state' => $state,
'response_type' => $responseType,
'scopes' => $scopes
'client' => $client,
'redirect_uri' => $redirectUri,
'state' => $state,
'response_type' => $responseType,
'scopes' => $scopes
];
}
/**
* Parse a new authorize request
*
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @param array $authParams The authorize request $_GET parameters
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @param array $authParams The authorize request $_GET parameters
*
* @return string An authorisation code
*/
public function newAuthorizeRequest($type, $typeId, $authParams = [])
@@ -139,7 +177,6 @@ class AuthCodeGrant extends AbstractGrant
$session = new SessionEntity($this->server);
$session->setOwner($type, $typeId);
$session->associateClient($authParams['client']);
$session->save();
// Create a new auth code
$authCode = new AuthCodeEntity($this->server);
@@ -149,8 +186,10 @@ class AuthCodeGrant extends AbstractGrant
foreach ($authParams['scopes'] as $scope) {
$authCode->associateScope($scope);
$session->associateScope($scope);
}
$session->save();
$authCode->setSession($session);
$authCode->save();
@@ -159,25 +198,23 @@ class AuthCodeGrant extends AbstractGrant
/**
* Complete the auth code grant
*
* @return array
*
* @throws
*/
public function completeFlow()
{
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', null);
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if (is_null($clientId)) {
$clientId = $this->server->getRequest()->getUser();
if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id');
}
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret', null);
if (is_null($clientSecret)) {
$clientSecret = $this->server->getRequest()->getPassword();
if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
if ($this->shouldRequireClientSecret() && is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
$redirectUri = $this->server->getRequest()->request->get('redirect_uri', null);
@@ -234,7 +271,7 @@ class AuthCodeGrant extends AbstractGrant
}
foreach ($session->getScopes() as $scope) {
$accessToken->associateScope($scope);
$accessToken->associateScope($scope);
}
$this->server->getTokenType()->setSession($session);
@@ -253,15 +290,14 @@ class AuthCodeGrant extends AbstractGrant
$code->expire();
// Save all the things
$session->save();
$accessToken->setSession($session);
$accessToken->save();
if ($this->server->hasGrantType('refresh_token')) {
if (isset($refreshToken) && $this->server->hasGrantType('refresh_token')) {
$refreshToken->setAccessToken($accessToken);
$refreshToken->save();
}
return $this->server->getTokenType()->generateResponse();
}
}
}

View File

@@ -14,9 +14,9 @@ namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Event;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Event;
/**
* Client credentials grant class
@@ -25,49 +25,51 @@ class ClientCredentialsGrant extends AbstractGrant
{
/**
* Grant identifier
*
* @var string
*/
protected $identifier = 'client_credentials';
/**
* Response type
*
* @var string
*/
protected $responseType = null;
/**
* AuthServer instance
* @var AuthServer
*
* @var \League\OAuth2\Server\AuthorizationServer
*/
protected $server = null;
/**
* Access token expires in override
*
* @var int
*/
protected $accessTokenTTL = null;
/**
* Complete the client credentials grant
*
* @return array
*
* @throws
*/
public function completeFlow()
{
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', null);
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if (is_null($clientId)) {
$clientId = $this->server->getRequest()->getUser();
if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id');
}
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret', null);
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
if (is_null($clientSecret)) {
$clientSecret = $this->server->getRequest()->getPassword();
if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
throw new Exception\InvalidRequestException('client_secret');
}
// Validate client ID and client secret
@@ -99,11 +101,11 @@ class ClientCredentialsGrant extends AbstractGrant
// Associate scopes with the session and access token
foreach ($scopes as $scope) {
$session->associateScope($scope);
$session->associateScope($scope);
}
foreach ($session->getScopes() as $scope) {
$accessToken->associateScope($scope);
$accessToken->associateScope($scope);
}
// Save everything

View File

@@ -11,13 +11,48 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\AuthorizationServer;
/**
* Grant type interface
*/
interface GrantTypeInterface
{
/**
* Return the identifier
*
* @return string
*/
public function getIdentifier();
/**
* Return the identifier
*
* @param string $identifier
*
* @return self
*/
public function setIdentifier($identifier);
/**
* Return the response type
*
* @return string
*/
public function getResponseType();
/**
* Inject the authorization server into the grant
*
* @param \League\OAuth2\Server\AuthorizationServer $server The authorization server instance
*
* @return self
*/
public function setAuthorizationServer(AuthorizationServer $server);
/**
* Complete the grant flow
*
* @return array
*/
public function completeFlow();

View File

@@ -11,13 +11,13 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Event;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Event;
/**
* Password grant class
@@ -26,31 +26,37 @@ class PasswordGrant extends AbstractGrant
{
/**
* Grant identifier
*
* @var string
*/
protected $identifier = 'password';
/**
* Response type
*
* @var string
*/
protected $responseType;
/**
* Callback to authenticate a user's name and password
*
* @var callable
*/
protected $callback;
/**
* Access token expires in override
*
* @var int
*/
protected $accessTokenTTL;
/**
* Set the callback to verify a user's username and password
* @param callable $callback The callback function
*
* @param callable $callback The callback function
*
* @return void
*/
public function setVerifyCredentialsCallback(callable $callback)
@@ -60,11 +66,14 @@ class PasswordGrant extends AbstractGrant
/**
* Return the callback function
*
* @return callable
*
* @throws
*/
protected function getVerifyCredentialsCallback()
{
if (is_null($this->callback) || ! is_callable($this->callback)) {
if (is_null($this->callback) || !is_callable($this->callback)) {
throw new Exception\ServerErrorException('Null or non-callable callback set on Password grant');
}
@@ -73,25 +82,23 @@ class PasswordGrant extends AbstractGrant
/**
* Complete the password grant
*
* @return array
*
* @throws
*/
public function completeFlow()
{
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', null);
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if (is_null($clientId)) {
$clientId = $this->server->getRequest()->getUser();
if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id');
}
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret', null);
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
if (is_null($clientSecret)) {
$clientSecret = $this->server->getRequest()->getPassword();
if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
throw new Exception\InvalidRequestException('client_secret');
}
// Validate client ID and client secret
@@ -141,11 +148,11 @@ class PasswordGrant extends AbstractGrant
// Associate scopes with the session and access token
foreach ($scopes as $scope) {
$session->associateScope($scope);
$session->associateScope($scope);
}
foreach ($session->getScopes() as $scope) {
$accessToken->associateScope($scope);
$accessToken->associateScope($scope);
}
$this->server->getTokenType()->setSession($session);

View File

@@ -11,16 +11,15 @@
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Event;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
/**
* Referesh token grant
* Refresh token grant
*/
class RefreshTokenGrant extends AbstractGrant
{
@@ -31,13 +30,31 @@ class RefreshTokenGrant extends AbstractGrant
/**
* Refresh token TTL (default = 604800 | 1 week)
*
* @var integer
*/
protected $refreshTokenTTL = 604800;
/**
* Rotate token (default = true)
*
* @var integer
*/
protected $refreshTokenRotate = true;
/**
* Whether to require the client secret when
* completing the flow.
*
* @var boolean
*/
protected $requireClientSecret = true;
/**
* Set the TTL of the refresh token
* @param int $refreshTokenTTL
*
* @param int $refreshTokenTTL
*
* @return void
*/
public function setRefreshTokenTTL($refreshTokenTTL)
@@ -47,6 +64,7 @@ class RefreshTokenGrant extends AbstractGrant
/**
* Get the TTL of the refresh token
*
* @return int
*/
public function getRefreshTokenTTL()
@@ -54,25 +72,61 @@ class RefreshTokenGrant extends AbstractGrant
return $this->refreshTokenTTL;
}
/**
* Set the rotation boolean of the refresh token
* @param bool $refreshTokenRotate
*/
public function setRefreshTokenRotation($refreshTokenRotate = true)
{
$this->refreshTokenRotate = $refreshTokenRotate;
}
/**
* Get rotation boolean of the refresh token
*
* @return bool
*/
public function shouldRotateRefreshTokens()
{
return $this->refreshTokenRotate;
}
/**
*
* @param bool $required True to require client secret during access
* token request. False if not. Default = true
*/
public function setRequireClientSecret($required)
{
$this->requireClientSecret = $required;
}
/**
* True if client secret is required during
* access token request. False if it isn't.
*
* @return bool
*/
public function shouldRequireClientSecret()
{
return $this->requireClientSecret;
}
/**
* {@inheritdoc}
*/
public function completeFlow()
{
$clientId = $this->server->getRequest()->request->get('client_id', null);
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if (is_null($clientId)) {
$clientId = $this->server->getRequest()->getUser();
if (is_null($clientId)) {
throw new Exception\InvalidRequestException('client_id');
}
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret', null);
if (is_null($clientSecret)) {
$clientSecret = $this->server->getRequest()->getPassword();
if (is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
if ($this->shouldRequireClientSecret() && is_null($clientSecret)) {
throw new Exception\InvalidRequestException('client_secret');
}
// Validate client ID and client secret
@@ -100,6 +154,11 @@ class RefreshTokenGrant extends AbstractGrant
throw new Exception\InvalidRefreshException();
}
// Ensure the old refresh token hasn't expired
if ($oldRefreshToken->isExpired() === true) {
throw new Exception\InvalidRefreshException();
}
$oldAccessToken = $oldRefreshToken->getAccessToken();
// Get the scopes for the original session
@@ -143,18 +202,22 @@ class RefreshTokenGrant extends AbstractGrant
$this->server->getTokenType()->setParam('access_token', $newAccessToken->getId());
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
// Expire the old refresh token
$oldRefreshToken->expire();
if ($this->shouldRotateRefreshTokens()) {
// Expire the old refresh token
$oldRefreshToken->expire();
// Generate a new refresh token
$newRefreshToken = new RefreshTokenEntity($this->server);
$newRefreshToken->setId(SecureKey::generate());
$newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time());
$newRefreshToken->setAccessToken($newAccessToken);
$newRefreshToken->save();
// Generate a new refresh token
$newRefreshToken = new RefreshTokenEntity($this->server);
$newRefreshToken->setId(SecureKey::generate());
$newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time());
$newRefreshToken->setAccessToken($newAccessToken);
$newRefreshToken->save();
$this->server->getTokenType()->setParam('refresh_token', $newRefreshToken->getId());
$this->server->getTokenType()->setParam('refresh_token', $newRefreshToken->getId());
} else {
$this->server->getTokenType()->setParam('refresh_token', $oldRefreshToken->getId());
}
return $this->server->getTokenType()->generateResponse();
}
}
}

View File

@@ -11,14 +11,15 @@
namespace League\OAuth2\Server;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Exception\AccessDeniedException;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\TokenType\Bearer;
use League\OAuth2\Server\Exception;
use Symfony\Component\HttpFoundation\Request;
use League\OAuth2\Server\TokenType\MAC;
/**
* OAuth 2.0 Resource Server
@@ -27,22 +28,26 @@ class ResourceServer extends AbstractServer
{
/**
* The access token
*
* @var \League\OAuth2\Server\Entity\AccessTokenEntity
*/
protected $accessToken;
/**
* The query string key which is used by clients to present the access token (default: access_token)
*
* @var string
*/
protected $tokenKey = 'access_token';
/**
* Initialise the resource server
* @param SessionInterface $sessionStorage
* @param AccessTokenInteface $accessTokenStorage
* @param ClientInterface $clientStorage
* @param ScopeInterface $scopeStorage
*
* @param \League\OAuth2\Server\Storage\SessionInterface $sessionStorage
* @param \League\OAuth2\Server\Storage\AccessTokenInterface $accessTokenStorage
* @param \League\OAuth2\Server\Storage\ClientInterface $clientStorage
* @param \League\OAuth2\Server\Storage\ScopeInterface $scopeStorage
*
* @return self
*/
public function __construct(
@@ -57,7 +62,7 @@ class ResourceServer extends AbstractServer
$this->setScopeStorage($scopeStorage);
// Set Bearer as the default token type
$this->setTokenType(new Bearer);
$this->setTokenType(new Bearer());
parent::__construct();
@@ -66,7 +71,9 @@ class ResourceServer extends AbstractServer
/**
* Sets the query string key for the access token.
* @param $key The new query string key
*
* @param string $key The new query string key
*
* @return self
*/
public function setIdKey($key)
@@ -78,36 +85,43 @@ class ResourceServer extends AbstractServer
/**
* Gets the access token
* @return string
*
* @return \League\OAuth2\Server\Entity\AccessTokenEntity
*/
public function getAccessToken()
{
return $this->accessToken->getId();
return $this->accessToken;
}
/**
* Checks if the access token is valid or not
* @param $headersOnly Limit Access Token to Authorization header only
*
* @param bool $headerOnly Limit Access Token to Authorization header
* @param \League\OAuth2\Server\Entity\AccessTokenEntity|null $accessToken Access Token
*
* @throws \League\OAuth2\Server\Exception\AccessDeniedException
* @throws \League\OAuth2\Server\Exception\InvalidRequestException
*
* @return bool
*/
public function isValidRequest($headersOnly = true, $accessToken = null)
public function isValidRequest($headerOnly = true, $accessToken = null)
{
$accessTokenString = ($accessToken !== null)
? $accessToken
: $this->determineAccessToken($headersOnly);
: $this->determineAccessToken($headerOnly);
// Set the access token
$this->accessToken = $this->getAccessTokenStorage()->get($accessTokenString);
// Ensure the access token exists
if (!$this->accessToken instanceof AccessTokenEntity) {
throw new Exception\AccessDeniedException;
throw new AccessDeniedException();
}
// Check the access token hasn't expired
// Ensure the auth code hasn't expired
if ($this->accessToken->isExpired() === true) {
throw new Exception\AccessDeniedException;
throw new AccessDeniedException();
}
return true;
@@ -115,22 +129,27 @@ class ResourceServer extends AbstractServer
/**
* Reads in the access token from the headers
* @param $headersOnly Limit Access Token to Authorization header only
* @throws Exception\MissingAccessTokenException Thrown if there is no access token presented
*
* @param bool $headerOnly Limit Access Token to Authorization header
*
* @throws \League\OAuth2\Server\Exception\InvalidRequestException Thrown if there is no access token presented
*
* @return string
*/
public function determineAccessToken($headersOnly = false)
public function determineAccessToken($headerOnly = false)
{
if ($this->getRequest()->headers->get('Authorization') !== null) {
$authHeader = $this->getRequest()->headers->get('Authorization');
if (!empty($authHeader)) {
$accessToken = $this->getTokenType()->determineAccessTokenInHeader($this->getRequest());
} elseif ($headersOnly === false) {
} elseif ($headerOnly === false && (! $this->getTokenType() instanceof MAC)) {
$accessToken = ($this->getRequest()->server->get('REQUEST_METHOD') === 'GET')
? $this->getRequest()->query->get($this->tokenKey)
: $this->getRequest()->request->get($this->tokenKey);
}
if (empty($accessToken)) {
throw new Exception\InvalidRequestException('access token');
throw new InvalidRequestException('access token');
}
return $accessToken;

View File

@@ -20,13 +20,17 @@ abstract class AbstractStorage implements StorageInterface
{
/**
* Server
*
* @var \League\OAuth2\Server\AbstractServer $server
*/
protected $server;
/**
* Set the server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function setServer(AbstractServer $server)
{
@@ -37,6 +41,7 @@ abstract class AbstractStorage implements StorageInterface
/**
* Return the server
*
* @return \League\OAuth2\Server\AbstractServer
*/
protected function getServer()

View File

@@ -12,8 +12,6 @@
namespace League\OAuth2\Server\Storage;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AbstractTokenEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
/**
@@ -23,39 +21,49 @@ interface AccessTokenInterface extends StorageInterface
{
/**
* Get an instance of Entity\AccessTokenEntity
* @param string $token The access token
* @return \League\OAuth2\Server\Entity\AccessTokenEntity
*
* @param string $token The access token
*
* @return \League\OAuth2\Server\Entity\AccessTokenEntity | null
*/
public function get($token);
/**
* Get the scopes for an access token
* @param \League\OAuth2\Server\Entity\AbstractTokenEntity $token The access token
* @return array Array of \League\OAuth2\Server\Entity\ScopeEntity
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[] Array of \League\OAuth2\Server\Entity\ScopeEntity
*/
public function getScopes(AbstractTokenEntity $token);
public function getScopes(AccessTokenEntity $token);
/**
* Creates a new access token
* @param string $token The access token
* @param integer $expireTime The expire time expressed as a unix timestamp
* @param string|integer $sessionId The session ID
* @return \League\OAuth2\Server\Entity\AccessToken
*
* @param string $token The access token
* @param integer $expireTime The expire time expressed as a unix timestamp
* @param string|integer $sessionId The session ID
*
* @return void
*/
public function create($token, $expireTime, $sessionId);
/**
* Associate a scope with an acess token
* @param \League\OAuth2\Server\Entity\AbstractTokenEntity $token The access token
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @return void
*/
public function associateScope(AbstractTokenEntity $token, ScopeEntity $scope);
public function associateScope(AccessTokenEntity $token, ScopeEntity $scope);
/**
* Delete an access token
* @param \League\OAuth2\Server\Entity\AbstractTokenEntity $token The access token to delete
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $token The access token to delete
*
* @return void
*/
public function delete(AbstractTokenEntity $token);
public function delete(AccessTokenEntity $token);
}

View File

@@ -21,13 +21,16 @@ interface AuthCodeInterface extends StorageInterface
{
/**
* Get the auth code
* @param string $code
* @return \League\OAuth2\Server\Entity\AuthCodeEntity
*
* @param string $code
*
* @return \League\OAuth2\Server\Entity\AuthCodeEntity | null
*/
public function get($code);
/**
* Create an auth code.
*
* @param string $token The token ID
* @param integer $expireTime Token expire time
* @param integer $sessionId Session identifier
@@ -39,22 +42,28 @@ interface AuthCodeInterface extends StorageInterface
/**
* Get the scopes for an access token
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
* @return array Array of \League\OAuth2\Server\Entity\ScopeEntity
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[] Array of \League\OAuth2\Server\Entity\ScopeEntity
*/
public function getScopes(AuthCodeEntity $token);
/**
* Associate a scope with an acess token
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The auth code
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @return void
*/
public function associateScope(AuthCodeEntity $token, ScopeEntity $scope);
/**
* Delete an access token
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The access token to delete
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $token The access token to delete
*
* @return void
*/
public function delete(AuthCodeEntity $token);

View File

@@ -20,18 +20,22 @@ interface ClientInterface extends StorageInterface
{
/**
* Validate a client
* @param string $clientId The client's ID
* @param string $clientSecret The client's secret (default = "null")
* @param string $redirectUri The client's redirect URI (default = "null")
* @param string $grantType The grant type used (default = "null")
* @return League\OAuth2\Server\Entity\ClientEntity
*
* @param string $clientId The client's ID
* @param string $clientSecret The client's secret (default = "null")
* @param string $redirectUri The client's redirect URI (default = "null")
* @param string $grantType The grant type used (default = "null")
*
* @return \League\OAuth2\Server\Entity\ClientEntity | null
*/
public function get($clientId, $clientSecret = null, $redirectUri = null, $grantType = null);
/**
* Get the client associated with a session
* @param \League\OAuth2\Server\Entity\SessionEntity $session The session
* @return \League\OAuth2\Server\Entity\ClientEntity
*
* @param \League\OAuth2\Server\Entity\SessionEntity $session The session
*
* @return \League\OAuth2\Server\Entity\ClientEntity | null
*/
public function getBySession(SessionEntity $session);
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* OAuth 2.0 MAC Token Interface
*
* @package league/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\Storage;
/**
* MacTokenInterface
*/
interface MacTokenInterface extends StorageInterface
{
/**
* Create a MAC key linked to an access token
* @param string $macKey
* @param string $accessToken
* @return void
*/
public function create($macKey, $accessToken);
/**
* Get a MAC key by access token
* @param string $accessToken
* @return string
*/
public function getByAccessToken($accessToken);
}

View File

@@ -20,23 +20,29 @@ interface RefreshTokenInterface extends StorageInterface
{
/**
* Return a new instance of \League\OAuth2\Server\Entity\RefreshTokenEntity
* @param string $token
* @return \League\OAuth2\Server\Entity\RefreshTokenEntity
*
* @param string $token
*
* @return \League\OAuth2\Server\Entity\RefreshTokenEntity | null
*/
public function get($token);
/**
* Create a new refresh token_name
* @param string $token
* @param integer $expireTime
* @param string $accessToken
*
* @param string $token
* @param integer $expireTime
* @param string $accessToken
*
* @return \League\OAuth2\Server\Entity\RefreshTokenEntity
*/
public function create($token, $expireTime, $accessToken);
/**
* Delete the refresh token
* @param \League\OAuth2\Server\Entity\RefreshTokenEntity $token
*
* @param \League\OAuth2\Server\Entity\RefreshTokenEntity $token
*
* @return void
*/
public function delete(RefreshTokenEntity $token);

View File

@@ -18,10 +18,12 @@ interface ScopeInterface extends StorageInterface
{
/**
* Return information about a scope
* @param string $scope The scope
* @param string $grantType The grant type used in the request (default = "null")
* @param string $clientId The client sending the request (default = "null")
* @return \League\OAuth2\Server\Entity\ScopeEntity
*
* @param string $scope The scope
* @param string $grantType The grant type used in the request (default = "null")
* @param string $clientId The client sending the request (default = "null")
*
* @return \League\OAuth2\Server\Entity\ScopeEntity | null
*/
public function get($scope, $grantType = null, $clientId = null);
}

View File

@@ -13,8 +13,8 @@ namespace League\OAuth2\Server\Storage;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
/**
* Session storage interface
@@ -23,39 +23,49 @@ interface SessionInterface extends StorageInterface
{
/**
* Get a session from an access token
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
* @return \League\OAuth2\Server\Entity\SessionEntity
*
* @param \League\OAuth2\Server\Entity\AccessTokenEntity $accessToken The access token
*
* @return \League\OAuth2\Server\Entity\SessionEntity | null
*/
public function getByAccessToken(AccessTokenEntity $accessToken);
/**
* Get a session from an auth code
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $authCode The auth code
* @return \League\OAuth2\Server\Entity\SessionEntity
*
* @param \League\OAuth2\Server\Entity\AuthCodeEntity $authCode The auth code
*
* @return \League\OAuth2\Server\Entity\SessionEntity | null
*/
public function getByAuthCode(AuthCodeEntity $authCode);
/**
* Get a session's scopes
*
* @param \League\OAuth2\Server\Entity\SessionEntity
* @return array Array of \League\OAuth2\Server\Entity\ScopeEntity
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[] Array of \League\OAuth2\Server\Entity\ScopeEntity
*/
public function getScopes(SessionEntity $session);
/**
* Create a new session
* @param string $ownerType Session owner's type (user, client)
* @param string $ownerId Session owner's ID
* @param string $clientId Client ID
* @param string $clientRedirectUri Client redirect URI (default = null)
*
* @param string $ownerType Session owner's type (user, client)
* @param string $ownerId Session owner's ID
* @param string $clientId Client ID
* @param string $clientRedirectUri Client redirect URI (default = null)
*
* @return integer The session's ID
*/
public function create($ownerType, $ownerId, $clientId, $clientRedirectUri = null);
/**
* Associate a scope with a session
* @param \League\OAuth2\Server\Entity\SessionEntity $scope The scope
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @param \League\OAuth2\Server\Entity\SessionEntity $session The session
* @param \League\OAuth2\Server\Entity\ScopeEntity $scope The scope
*
* @return void
*/
public function associateScope(SessionEntity $session, ScopeEntity $scope);

View File

@@ -20,6 +20,7 @@ interface StorageInterface
{
/**
* Set the server
*
* @param \League\OAuth2\Server\AbstractServer $server
*/
public function setServer(AbstractServer $server);

View File

@@ -11,7 +11,6 @@
namespace League\OAuth2\Server\TokenType;
use Symfony\Component\HttpFoundation\Request;
use League\OAuth2\Server\AbstractServer;
use League\OAuth2\Server\Entity\SessionEntity;
@@ -19,46 +18,47 @@ abstract class AbstractTokenType
{
/**
* Response array
*
* @var array
*/
protected $response = [];
/**
* Server
*
* @var \League\OAuth2\Server\AbstractServer $server
*/
protected $server;
/**
* Server
*
* @var \League\OAuth2\Server\Entity\SessionEntity $session
*/
protected $session;
/**
* Set the server
* @param \League\OAuth2\Server\AbstractServer $server
* {@inheritdoc}
*/
public function setServer(AbstractServer $server)
{
$this->server = $server;
return $this;
}
/**
* Set the session entity
* @param \League\OAuth2\Server\Entity\SessionEntity $session
* {@inheritdoc}
*/
public function setSession(SessionEntity $session)
{
$this->session = $session;
return $this;
}
/**
* Set a key/value response pair
* @param string $key
* @param mixed $value
* {@inheritdoc}
*/
public function setParam($key, $value)
{
@@ -66,19 +66,10 @@ abstract class AbstractTokenType
}
/**
* Get a key from the response array
* @param string $key
* @return mixed
* {@inheritdoc}
*/
public function getParam($key)
{
return isset($this->response[$key]) ? $this->response[$key] : null;
}
/**
* Determine the access token in the authorization header
* @param \Symfony\Component\HttpFoundation\Request $request
* @return string
*/
abstract public function determineAccessTokenInHeader(Request $request);
}

View File

@@ -23,7 +23,7 @@ class Bearer extends AbstractTokenType implements TokenTypeInterface
$return = [
'access_token' => $this->getParam('access_token'),
'token_type' => 'Bearer',
'expires_in' => $this->getParam('expires_in')
'expires_in' => $this->getParam('expires_in'),
];
if (!is_null($this->getParam('refresh_token'))) {
@@ -38,9 +38,16 @@ class Bearer extends AbstractTokenType implements TokenTypeInterface
*/
public function determineAccessTokenInHeader(Request $request)
{
$header = $request->headers->get('Authorization');
$accessToken = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));
if ($request->headers->has('Authorization') === false) {
return;
}
return ($accessToken === 'Bearer') ? '' : $accessToken;
$header = $request->headers->get('Authorization');
if (substr($header, 0, 7) !== 'Bearer ') {
return;
}
return trim(substr($header, 7));
}
}

156
src/TokenType/MAC.php Normal file
View File

@@ -0,0 +1,156 @@
<?php
/**
* OAuth 2.0 MAC Token Type
*
* @package league/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) Alex Bilbie
* @license http://mit-license.org/
* @link https://github.com/thephpleague/oauth2-server
*/
namespace League\OAuth2\Server\TokenType;
use League\OAuth2\Server\Util\SecureKey;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
/**
* MAC Token Type
*/
class MAC extends AbstractTokenType implements TokenTypeInterface
{
/**
* {@inheritdoc}
*/
public function generateResponse()
{
$macKey = SecureKey::generate();
$this->server->getMacStorage()->create($macKey, $this->getParam('access_token'));
$response = [
'access_token' => $this->getParam('access_token'),
'token_type' => 'mac',
'expires_in' => $this->getParam('expires_in'),
'mac_key' => $macKey,
'mac_algorithm' => 'hmac-sha-256',
];
if (!is_null($this->getParam('refresh_token'))) {
$response['refresh_token'] = $this->getParam('refresh_token');
}
return $response;
}
/**
* {@inheritdoc}
*/
public function determineAccessTokenInHeader(Request $request)
{
if ($request->headers->has('Authorization') === false) {
return;
}
$header = $request->headers->get('Authorization');
if (substr($header, 0, 4) !== 'MAC ') {
return;
}
// Find all the parameters expressed in the header
$paramsRaw = explode(',', substr($header, 4));
$params = new ParameterBag();
array_map(function ($param) use (&$params) {
$param = trim($param);
preg_match_all('/([a-zA-Z]*)="([\w=\/+]*)"/', $param, $matches);
// @codeCoverageIgnoreStart
if (count($matches) !== 3) {
return;
}
// @codeCoverageIgnoreEnd
$key = reset($matches[1]);
$value = trim(reset($matches[2]));
if (empty($value)) {
return;
}
$params->set($key, $value);
}, $paramsRaw);
// Validate parameters
if ($params->has('id') === false || $params->has('ts') === false || $params->has('nonce') === false || $params->has('mac') === false) {
return;
}
if (abs($params->get('ts') - time()) > 300) {
return;
}
$accessToken = $params->get('id');
$timestamp = (int) $params->get('ts');
$nonce = $params->get('nonce');
$signature = $params->get('mac');
// Try to find the MAC key for the access token
$macKey = $this->server->getMacStorage()->getByAccessToken($accessToken);
if ($macKey === null) {
return;
}
// Calculate and compare the signature
$calculatedSignatureParts = [
$timestamp,
$nonce,
strtoupper($request->getMethod()),
$request->getRequestUri(),
$request->getHost(),
$request->getPort(),
];
if ($params->has('ext')) {
$calculatedSignatureParts[] = $params->get('ext');
}
$calculatedSignature = base64_encode(
hash_hmac(
'sha256',
implode("\n", $calculatedSignatureParts),
$macKey,
true // raw_output: outputs raw binary data
)
);
// Return the access token if the signature matches
return ($this->hash_equals($calculatedSignature, $signature)) ? $accessToken : null;
}
/**
* Prevent timing attack
* @param string $knownString
* @param string $userString
* @return bool
*/
private function hash_equals($knownString, $userString)
{
if (function_exists('\hash_equals')) {
return \hash_equals($knownString, $userString);
}
if (strlen($knownString) !== strlen($userString)) {
return false;
}
$len = strlen($knownString);
$result = 0;
for ($i = 0; $i < $len; $i++) {
$result |= (ord($knownString[$i]) ^ ord($userString[$i]));
}
// They are only identical strings if $result is exactly 0...
return 0 === $result;
}
}

View File

@@ -11,11 +11,58 @@
namespace League\OAuth2\Server\TokenType;
use League\OAuth2\Server\AbstractServer;
use League\OAuth2\Server\Entity\SessionEntity;
use Symfony\Component\HttpFoundation\Request;
interface TokenTypeInterface
{
/**
* Generate a response
*
* @return array
*/
public function generateResponse();
/**
* Set the server
*
* @param \League\OAuth2\Server\AbstractServer $server
*
* @return self
*/
public function setServer(AbstractServer $server);
/**
* Set a key/value response pair
*
* @param string $key
* @param mixed $value
*/
public function setParam($key, $value);
/**
* Get a key from the response array
*
* @param string $key
*
* @return mixed
*/
public function getParam($key);
/**
* @param \League\OAuth2\Server\Entity\SessionEntity $session
*
* @return self
*/
public function setSession(SessionEntity $session);
/**
* Determine the access token in the authorization header
*
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return string
*/
public function determineAccessTokenInHeader(Request $request);
}

View File

@@ -18,18 +18,19 @@ class DefaultAlgorithm implements KeyAlgorithmInterface
*/
public function generate($len = 40)
{
// We generate twice as many bytes here because we want to ensure we have
// enough after we base64 encode it to get the length we need because we
// take out the "/", "+", and "=" characters.
$bytes = openssl_random_pseudo_bytes($len * 2, $strong);
$stripped = '';
do {
$bytes = openssl_random_pseudo_bytes($len, $strong);
// We want to stop execution if the key fails because, well, that is bad.
if ($bytes === false || $strong === false) {
// @codeCoverageIgnoreStart
throw new \Exception('Error Generating Key');
// @codeCoverageIgnoreEnd
}
// We want to stop execution if the key fails because, well, that is bad.
if ($bytes === false || $strong === false) {
// @codeCoverageIgnoreStart
throw new \Exception('Error Generating Key');
// @codeCoverageIgnoreEnd
}
$stripped .= str_replace(['/', '+', '='], '', base64_encode($bytes));
} while (strlen($stripped) < $len);
return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $len);
return substr($stripped, 0, $len);
}
}

View File

@@ -15,7 +15,9 @@ interface KeyAlgorithmInterface
{
/**
* Generate a new unique code
* @param integer $len Length of the generated code
*
* @param integer $len Length of the generated code
*
* @return string
*/
public function generate($len);

View File

@@ -18,12 +18,14 @@ class RedirectUri
{
/**
* Generate a new redirect uri
* @param string $uri The base URI
* @param array $params The query string parameters
* @param string $queryDelimeter The query string delimeter (default: "?")
*
* @param string $uri The base URI
* @param array $params The query string parameters
* @param string $queryDelimeter The query string delimeter (default: "?")
*
* @return string The updated URI
*/
public static function make($uri, $params = array(), $queryDelimeter = '?')
public static function make($uri, $params = [], $queryDelimeter = '?')
{
$uri .= (strstr($uri, $queryDelimeter) === false) ? $queryDelimeter : '&';

View File

@@ -23,7 +23,9 @@ class SecureKey
/**
* Generate a new unique code
* @param integer $len Length of the generated code
*
* @param integer $len Length of the generated code
*
* @return string
*/
public static function generate($len = 40)

View File

@@ -6,4 +6,4 @@ response:
headers:
-
key: Location
valueRegex: /http:\/\/example.com\/redirect\?code=([a-zA-Z0-9]*)/
valueRegex: /http:\/\/example.com\/redirect\?code=([a-zA-Z0-9]*)/

View File

@@ -64,4 +64,4 @@ response:
valueRegex: /([a-zA-Z0-9]*)/
-
key: token_type
value: Bearer
value: Bearer

View File

@@ -85,4 +85,4 @@ response:
valueRegex: /([a-zA-Z0-9]*)/
-
key: token_type
value: Bearer
value: Bearer

View File

@@ -13,4 +13,4 @@ response:
value: "invalid_request"
-
key: message
value: "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."
value: "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."

View File

@@ -13,4 +13,4 @@ response:
value: "access_denied"
-
key: message
value: "The resource owner or authorization server denied the request."
value: "The resource owner or authorization server denied the request."

View File

@@ -17,4 +17,4 @@ response:
value: "access_denied"
-
key: message
value: "The resource owner or authorization server denied the request."
value: "The resource owner or authorization server denied the request."

View File

@@ -23,4 +23,4 @@ response:
value: iamgod
-
key: client_id
value: testclient
value: testclient

View File

@@ -19,4 +19,4 @@ response:
value: iamgod
-
key: client_id
value: testclient
value: testclient

View File

@@ -29,4 +29,4 @@ response:
value: Phil Sturgeon
-
key: 1.photo
valueType: string
valueType: string

View File

@@ -29,4 +29,4 @@ response:
value: Phil Sturgeon
-
key: 1.email
valueType: string
valueType: string

View File

@@ -10,7 +10,7 @@ class AbstractServerTest extends \PHPUnit_Framework_TestCase
{
$server = new StubAbstractServer();
$var = 0;
$server->addEventListener('event.name', function() use ($var) {
$server->addEventListener('event.name', function () use ($var) {
$var++;
$this->assertSame(1, $var);
});
@@ -18,11 +18,9 @@ class AbstractServerTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($server->getRequest() instanceof \Symfony\Component\HttpFoundation\Request);
$this->assertTrue($server->getEventEmitter() instanceof \League\Event\Emitter);
$server2 = new StubAbstractServer();
$server2->setRequest((new \Symfony\Component\HttpFoundation\Request));
$server2->setRequest((new \Symfony\Component\HttpFoundation\Request()));
$server2->setEventEmitter(1);
$this->assertTrue($server2->getRequest() instanceof \Symfony\Component\HttpFoundation\Request);
}
}

View File

@@ -5,17 +5,17 @@ namespace LeagueTests;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Grant\GrantTypeInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use \Mockery as M;
use Mockery as M;
class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$server->requireScopeParam(true);
$server->requireStateParam(true);
$server->setDefaultScope('foobar');
$server->setScopeDelimeter(',');
$server->setScopeDelimiter(',');
$server->setAccessTokenTTL(1);
$grant = M::mock('League\OAuth2\Server\Grant\GrantTypeInterface');
@@ -36,14 +36,14 @@ class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($server->stateParamRequired());
$this->assertTrue($server->getScopeStorage() instanceof ScopeInterface);
$this->assertEquals('foobar', $server->getDefaultScope());
$this->assertEquals(',', $server->getScopeDelimeter());
$this->assertEquals(',', $server->getScopeDelimiter());
$this->assertEquals(1, $server->getAccessTokenTTL());
}
public function testInvalidGrantType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidGrantException');
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$server->getGrantType('foobar');
}
@@ -57,7 +57,7 @@ class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'foobar';
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$server->addGrantType($grant);
$this->assertTrue($server->issueAccessToken());
@@ -66,7 +66,7 @@ class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
public function testIssueAccessTokenEmptyGrantType()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$this->assertTrue($server->issueAccessToken());
}
@@ -76,7 +76,7 @@ class AuthorizationServerTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'foobar';
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$this->assertTrue($server->issueAccessToken());
}
}

View File

@@ -1,5 +1,5 @@
<?php
if (! @include_once __DIR__ . '/../../vendor/autoload.php') {
if (! @include_once __DIR__.'/../../vendor/autoload.php') {
exit("You must set up the project dependencies, run the following commands:\n> wget http://getcomposer.org/composer.phar\n> php composer.phar install\n");
}

View File

@@ -2,13 +2,13 @@
namespace LeagueTests\Entity;
use LeagueTests\Stubs\StubAbstractTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\AuthorizationServer;
use \Mockery as M;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use LeagueTests\Stubs\StubAbstractTokenEntity;
use Mockery as M;
class AbstractTokenTest extends \PHPUnit_Framework_TestCase
class AbstractTokenEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
@@ -93,7 +93,7 @@ class AbstractTokenTest extends \PHPUnit_Framework_TestCase
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1', 'description' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar'])
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar']),
];
$result = $method->invokeArgs($entity, [$scopes]);

View File

@@ -2,12 +2,12 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use \Mockery as M;
use Mockery as M;
class AccessTokenTest extends \PHPUnit_Framework_TestCase
class AccessTokenEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSave()
{
@@ -20,7 +20,7 @@ class AccessTokenTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');

View File

@@ -2,13 +2,13 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\AuthorizationServer;
use \Mockery as M;
use Mockery as M;
class AuthCodeTest extends \PHPUnit_Framework_TestCase
class AuthCodeEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
@@ -37,7 +37,7 @@ class AuthCodeTest extends \PHPUnit_Framework_TestCase
$authCodeStorage->shouldReceive('associateScope');
$authCodeStorage->shouldReceive('setServer');
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getAuthCodeStorage')->andReturn($authCodeStorage);

View File

@@ -3,9 +3,9 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\ClientEntity;
use \Mockery as M;
use Mockery as M;
class ClientTest extends \PHPUnit_Framework_TestCase
class ClientEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
@@ -14,7 +14,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
'id' => 'foobar',
'secret' => 'barfoo',
'name' => 'Test Client',
'redirectUri' => 'http://foo/bar'
'redirectUri' => 'http://foo/bar',
]);
$this->assertEquals('foobar', $client->getId());

View File

@@ -2,11 +2,11 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use \Mockery as M;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class RefreshTokenEntityTest extends \PHPUnit_Framework_TestCase
{
@@ -55,7 +55,7 @@ class RefreshTokenEntityTest extends \PHPUnit_Framework_TestCase
(new AccessTokenEntity($server))->setId('foobar')
);
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getAccessTokenStorage')->andReturn($accessTokenStorage);

View File

@@ -3,16 +3,16 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\Entity\ScopeEntity;
use \Mockery as M;
use Mockery as M;
class ScopeTest extends \PHPUnit_Framework_TestCase
class ScopeEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$scope = (new ScopeEntity($server))->hydrate([
'id' => 'foobar',
'description' => 'barfoo'
'description' => 'barfoo',
]);
$this->assertEquals('foobar', $scope->getId());

View File

@@ -2,15 +2,15 @@
namespace LeagueTests\Entity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\AuthorizationServer;
use \Mockery as M;
use League\OAuth2\Server\Entity\SessionEntity;
use Mockery as M;
class SessionTest extends \PHPUnit_Framework_TestCase
class SessionEntityTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
@@ -60,7 +60,7 @@ class SessionTest extends \PHPUnit_Framework_TestCase
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2'])
(new ScopeEntity($server))->hydrate(['id' => 'scope2']),
];
$result = $method->invokeArgs($entity, [$scopes]);
@@ -132,7 +132,7 @@ class SessionTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->shouldReceive('getSessionStorage')->andReturn($sessionStorage);

View File

@@ -2,13 +2,13 @@
namespace LeagueTests;
use \Mockery as M;
use League\OAuth2\Server\Exception\OAuthException;
class OAuthExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testGetHttpHeaders()
{
$exception = new \League\OAuth2\Server\Exception\OAuthException();
$exception = new OAuthException();
$exception->httpStatusCode = 400;
$this->assertSame($exception->getHttpHeaders(), ['HTTP/1.1 400 Bad Request']);
@@ -25,7 +25,7 @@ class OAuthExceptionTest extends \PHPUnit_Framework_TestCase
public function testShouldRedirect()
{
$exception = new \League\OAuth2\Server\Exception\OAuthException();
$exception = new OAuthException();
$exception->redirectUri = 'http://example.com/';
$exception->errorType = 'Error';
$this->assertTrue($exception->shouldRedirect());

View File

@@ -2,11 +2,11 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\Grant;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\Grant;
use LeagueTests\Stubs\StubAbstractGrant;
use Mockery as M;
@@ -14,9 +14,9 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setIdentifier('foobar');
$grant->setAccessTokenTTL(300);
$grant->setAuthorizationServer($server);
@@ -31,14 +31,14 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
{
$server = M::mock('League\OAuth2\Server\AbstractServer');
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$reflectedGrant = new \ReflectionClass('LeagueTests\Stubs\StubAbstractGrant');
$method = $reflectedGrant->getMethod('formatScopes');
$method->setAccessible(true);
$scopes = [
(new ScopeEntity($server))->hydrate(['id' => 'scope1', 'description' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar'])
(new ScopeEntity($server))->hydrate(['id' => 'scope2', 'description' => 'bar']),
];
$result = $method->invokeArgs($grant, [$scopes]);
@@ -51,7 +51,7 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
public function testValidateScopes()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
@@ -61,14 +61,14 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$this->assertEquals(
[
'foo' => (new ScopeEntity($server))->hydrate(['id' => 'foo'])
'foo' => (new ScopeEntity($server))->hydrate(['id' => 'foo']),
],
$grant->validateScopes('foo', $client)
);
@@ -81,11 +81,11 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$server->requireScopeParam(true);
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
@@ -101,10 +101,10 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(null);
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$server->setScopeStorage($scopeStorage);
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
@@ -114,7 +114,7 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
public function testValidateScopesDefaultScope()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
@@ -127,7 +127,7 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
$server->setScopeStorage($scopeStorage);
$server->setDefaultScope('foo');
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
@@ -137,7 +137,7 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
public function testValidateScopesDefaultScopeArray()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
@@ -150,7 +150,7 @@ class AbstractGrantTest extends \PHPUnit_Framework_TestCase
$server->setScopeStorage($scopeStorage);
$server->setDefaultScope(['foo', 'bar']);
$grant = new StubAbstractGrant;
$grant = new StubAbstractGrant();
$grant->setAuthorizationServer($server);
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);

View File

@@ -2,21 +2,21 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\Grant\AuthCodeGrant;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\AuthCodeEntity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Exception\InvalidRequestException;
use Mockery as M;
class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetAuthTokenTTL()
{
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$grant->setAuthTokenTTL(100);
$class = new \ReflectionClass($grant);
@@ -30,25 +30,24 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$_GET = [];
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
}
public function testCheckAuthoriseParamsMissingRedirectUri()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRequestException');
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$_GET = [
'client_id' => 'testapp'
'client_id' => 'testapp',
];
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
@@ -61,11 +60,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'response_type' => 'code'
'response_type' => 'code',
];
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -83,9 +82,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar'
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -94,7 +93,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->requireStateParam(true);
$server->addGrantType($grant);
@@ -107,9 +106,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar'
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -118,7 +117,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
@@ -131,9 +130,9 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_GET = [
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'response_type' => 'foobar'
'response_type' => 'foobar',
];
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -142,7 +141,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
);
$server->setClientStorage($clientStorage);
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$grant->checkAuthorizeParams();
@@ -156,11 +155,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'response_type' => 'code',
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -197,11 +196,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'response_type' => 'code',
'client_id' => 'testapp',
'redirect_uri' => 'http://foo/bar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -213,7 +212,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('associateScope');
@@ -221,7 +220,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -249,11 +248,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
public function testNewAuthoriseRequest()
{
$server = new AuthorizationServer;
$server = new AuthorizationServer();
$client = (new ClientEntity($server))->hydrate(['id' => 'testapp']);
$scope = (new ScopeEntity($server))->hydrate(['id' => 'foo']);
$grant = new AuthCodeGrant;
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
@@ -284,12 +283,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'authorization_code';
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
@@ -298,11 +296,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp'
'client_id' => 'testapp',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -315,11 +313,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -333,11 +331,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar'
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -357,11 +355,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'authorization_code',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar'
'redirect_uri' => 'http://foo/bar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -406,11 +404,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar'
'code' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -455,11 +453,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar'
'code' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -506,11 +504,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foobar'
'code' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -555,11 +553,11 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foo'
'code' => 'foo',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -581,7 +579,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
@@ -589,7 +587,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
@@ -605,7 +603,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
(new AuthCodeEntity($server))->setId('foobar')->setRedirectUri('http://foo/bar')->setExpireTime(time() + 300)
);
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$server->setClientStorage($clientStorage);
@@ -625,12 +623,12 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'redirect_uri' => 'http://foo/bar',
'code' => 'foo'
'code' => 'foo',
];
$server = new AuthorizationServer;
$grant = new AuthCodeGrant;
$rtgrant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new AuthCodeGrant();
$rtgrant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -652,7 +650,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
(new SessionEntity($server))->setId('foobar')
);
$sessionStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
@@ -660,7 +658,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('associateScope');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
@@ -676,7 +674,7 @@ class AuthCodeGrantTest extends \PHPUnit_Framework_TestCase
(new AuthCodeEntity($server))->setId('foobar')->setRedirectUri('http://foo/bar')->setExpireTime(time() + 300)
);
$authCodeStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');

View File

@@ -2,11 +2,11 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
use Mockery as M;
class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
@@ -17,12 +17,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'client_credentials';
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
@@ -31,11 +30,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp'
'client_id' => 'testapp',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -48,11 +47,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -72,11 +71,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -112,11 +111,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -160,11 +159,11 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -176,7 +175,7 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
@@ -187,7 +186,7 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -214,16 +213,16 @@ class ClientCredentialsGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'client_credentials',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new ClientCredentialsGrant;
$server = new AuthorizationServer();
$grant = new ClientCredentialsGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andThrow(
new \League\OAuth2\Server\Exception\UnauthorizedClientException
new \League\OAuth2\Server\Exception\UnauthorizedClientException()
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');

View File

@@ -2,12 +2,12 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Grant\PasswordGrant;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\AuthorizationServer;
use Mockery as M;
class PasswordGrantTest extends \PHPUnit_Framework_TestCase
@@ -18,12 +18,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'password';
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowMissingClientSecret()
@@ -32,11 +31,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp'
'client_id' => 'testapp',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -49,11 +48,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -72,11 +71,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -115,11 +114,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'password',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'foo'
'username' => 'foo',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -159,11 +158,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'foo',
'password' => 'foobar'
'password' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -204,11 +203,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_secret' => 'foobar',
'username' => 'foo',
'password' => 'foobar',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -251,11 +250,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'username' => 'username',
'password' => 'password'
'password' => 'password',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -301,11 +300,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password'
'password' => 'password',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -317,7 +316,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('associateScope');
@@ -325,7 +324,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -355,11 +354,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password'
'password' => 'password',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -371,7 +370,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
@@ -382,7 +381,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -416,11 +415,11 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
'client_secret' => 'foobar',
'scope' => 'foo',
'username' => 'username',
'password' => 'password'
'password' => 'password',
];
$server = new AuthorizationServer;
$grant = new PasswordGrant;
$server = new AuthorizationServer();
$grant = new PasswordGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -432,7 +431,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('create')->andreturn(123);
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))->setId('foobar')
@@ -443,7 +442,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -469,7 +468,7 @@ class PasswordGrantTest extends \PHPUnit_Framework_TestCase
});
$server->addGrantType($grant);
$server->addGrantType(new RefreshTokenGrant);
$server->addGrantType(new RefreshTokenGrant());
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));

View File

@@ -2,20 +2,20 @@
namespace LeagueTests\Grant;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Grant\RefreshTokenGrant;
use Mockery as M;
class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
{
public function testSetRefreshTokenTTL()
{
$grant = new RefreshTokenGrant;
$grant = new RefreshTokenGrant();
$grant->setRefreshTokenTTL(86400);
$property = new \ReflectionProperty($grant, 'refreshTokenTTL');
@@ -30,8 +30,8 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$_POST['grant_type'] = 'refresh_token';
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -43,11 +43,11 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp'
'client_id' => 'testapp',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();
@@ -60,11 +60,11 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar'
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -86,8 +86,8 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'client_secret' => 'foobar',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -118,11 +118,11 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'meh'
'refresh_token' => 'meh',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -152,11 +152,11 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token'
'refresh_token' => 'refresh_token',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
@@ -180,7 +180,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -190,7 +190,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
@@ -221,11 +221,11 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'foo'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
@@ -251,7 +251,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -261,7 +261,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
@@ -285,18 +285,20 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(isset($response['expires_in']));
}
public function testCompleteFlowRequestScopesInvalid()
public function testCompleteFlowExpiredRefreshToken()
{
$this->setExpectedException('League\OAuth2\Server\Exception\InvalidRefreshException');
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'blah'
'scope' => 'foo',
];
$server = new AuthorizationServer;
$grant = new RefreshTokenGrant;
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
@@ -322,7 +324,7 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
@@ -335,6 +337,72 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
(new RefreshTokenEntity($server))
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$server->issueAccessToken();
}
public function testCompleteFlowRequestScopesInvalid()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
'scope' => 'blah',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$oldSession = (new SessionEntity($server))->associateScope((new ScopeEntity($server))->hydrate(['id' => 'foo']));
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
$oldSession
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
@@ -353,4 +421,150 @@ class RefreshTokenGrantTest extends \PHPUnit_Framework_TestCase
$server->issueAccessToken();
}
public function testCompleteFlowRotateRefreshToken()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'client_secret' => 'foobar',
'refresh_token' => 'refresh_token',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setId('refresh_token')->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertNotEquals($response['refresh_token'], $_POST['refresh_token']);
$grant->setRefreshTokenRotation(false);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
$this->assertEquals($response['refresh_token'], $_POST['refresh_token']);
}
public function testCompleteFlowShouldRequireClientSecret()
{
$_POST = [
'grant_type' => 'refresh_token',
'client_id' => 'testapp',
'refresh_token' => 'refresh_token',
];
$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$grant->setRequireClientSecret(false);
$clientStorage = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$clientStorage->shouldReceive('setServer');
$clientStorage->shouldReceive('get')->andReturn(
(new ClientEntity($server))->hydrate(['id' => 'testapp'])
);
$sessionStorage = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$sessionStorage->shouldReceive('setServer');
$sessionStorage->shouldReceive('getScopes')->shouldReceive('getScopes')->andReturn([]);
$sessionStorage->shouldReceive('associateScope');
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
(new SessionEntity($server))
);
$accessTokenStorage = M::mock('League\OAuth2\Server\Storage\AccessTokenInterface');
$accessTokenStorage->shouldReceive('setServer');
$accessTokenStorage->shouldReceive('get')->andReturn(
(new AccessTokenEntity($server))
);
$accessTokenStorage->shouldReceive('delete');
$accessTokenStorage->shouldReceive('create');
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
]);
$accessTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage = M::mock('League\OAuth2\Server\Storage\RefreshTokenInterface');
$refreshTokenStorage->shouldReceive('setServer');
$refreshTokenStorage->shouldReceive('associateScope');
$refreshTokenStorage->shouldReceive('delete');
$refreshTokenStorage->shouldReceive('create');
$refreshTokenStorage->shouldReceive('get')->andReturn(
(new RefreshTokenEntity($server))->setId('refresh_token')->setExpireTime(time() + 86400)
);
$scopeStorage = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
$scopeStorage->shouldReceive('setServer');
$scopeStorage->shouldReceive('get')->andReturn(
(new ScopeEntity($server))->hydrate(['id' => 'foo'])
);
$server->setClientStorage($clientStorage);
$server->setScopeStorage($scopeStorage);
$server->setSessionStorage($sessionStorage);
$server->setAccessTokenStorage($accessTokenStorage);
$server->setRefreshTokenStorage($refreshTokenStorage);
$server->addGrantType($grant);
$response = $server->issueAccessToken();
$this->assertTrue(array_key_exists('access_token', $response));
$this->assertTrue(array_key_exists('refresh_token', $response));
$this->assertTrue(array_key_exists('token_type', $response));
$this->assertTrue(array_key_exists('expires_in', $response));
}
}

View File

@@ -2,12 +2,12 @@
namespace LeagueTests;
use League\OAuth2\Server\ResourceServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\Entity\ClientEntity;
use League\OAuth2\Server\Entity\ScopeEntity;
use \Mockery as M;
use League\OAuth2\Server\Entity\SessionEntity;
use League\OAuth2\Server\ResourceServer;
use Mockery as M;
class ResourceServerTest extends \PHPUnit_Framework_TestCase
{
@@ -77,7 +77,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'HTTP_AUTHORIZATION' => 'Bearer'
'HTTP_AUTHORIZATION' => 'Bearer',
]);
$server->setRequest($request);
@@ -137,7 +137,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$server->setIdKey('at');
$server->addEventListener('session.owner', function($event) {
$server->addEventListener('session.owner', function ($event) {
$this->assertTrue($event->getSession() instanceof \League\OAuth2\Server\Entity\SessionEntity);
});
@@ -147,7 +147,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'bar'])
(new ScopeEntity($server))->hydrate(['id' => 'bar']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
@@ -160,7 +160,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'Authorization' => 'Bearer abcdef'
'Authorization' => 'Bearer abcdef',
]);
$server->setRequest($request);
@@ -194,7 +194,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$server->setIdKey('at');
$server->addEventListener('session.owner', function($event) {
$server->addEventListener('session.owner', function ($event) {
$this->assertTrue($event->getSession() instanceof \League\OAuth2\Server\Entity\SessionEntity);
});
@@ -204,7 +204,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$accessTokenStorage->shouldReceive('getScopes')->andReturn([
(new ScopeEntity($server))->hydrate(['id' => 'foo']),
(new ScopeEntity($server))->hydrate(['id' => 'bar'])
(new ScopeEntity($server))->hydrate(['id' => 'bar']),
]);
$sessionStorage->shouldReceive('getByAccessToken')->andReturn(
@@ -217,7 +217,7 @@ class ResourceServerTest extends \PHPUnit_Framework_TestCase
$request = new \Symfony\Component\HttpFoundation\Request();
$request->headers = new \Symfony\Component\HttpFoundation\ParameterBag([
'Authorization' => 'Bearer abcdef'
'Authorization' => 'Bearer abcdef',
]);
$server->setRequest($request);

View File

@@ -2,19 +2,19 @@
namespace LeagueTests\Storage;
use LeagueTests\Stubs\StubAbstractStorage;
use LeagueTests\Stubs\StubAbstractServer;
use LeagueTests\Stubs\StubAbstractStorage;
class AdapterStorageTest extends \PHPUnit_Framework_TestCase
class AbstractStorageTest extends \PHPUnit_Framework_TestCase
{
public function testSetGet()
{
$storage = new StubAbstractStorage;
$storage = new StubAbstractStorage();
$reflector = new \ReflectionClass($storage);
$setMethod = $reflector->getMethod('setServer');
$setMethod->setAccessible(true);
$setMethod->invokeArgs($storage, [new StubAbstractServer]);
$setMethod->invokeArgs($storage, [new StubAbstractServer()]);
$getMethod = $reflector->getMethod('getServer');
$getMethod->setAccessible(true);

View File

@@ -4,5 +4,5 @@ namespace LeagueTests\Stubs;
class StubAbstractServer extends \League\OAuth2\Server\AbstractServer
{
//
}

View File

@@ -4,5 +4,5 @@ namespace LeagueTests\Stubs;
class StubAbstractStorage extends \League\OAuth2\Server\Storage\AbstractStorage
{
//
}

View File

@@ -2,17 +2,17 @@
namespace LeagueTests\Stubs;
use \League\OAuth2\Server\Entity\AbstractTokenEntity;
use League\OAuth2\Server\Entity\AbstractTokenEntity;
class StubAbstractTokenEntity extends AbstractTokenEntity
{
public function expire()
{
//
}
public function save()
{
//
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace LeagueTests\TokenType;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Entity\AccessTokenEntity;
use League\OAuth2\Server\TokenType\MAC;
use Mockery as M;
use Symfony\Component\HttpFoundation\Request;
class MacTest extends \PHPUnit_Framework_TestCase
{
public function testGenerateResponse()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('create');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$tokenType = new MAC();
$tokenType->setServer($server);
$accessToken = new AccessTokenEntity($server);
$accessToken->setId(uniqid());
$accessToken->setExpireTime(time());
$tokenType->setParam('access_token', $accessToken->getId());
$tokenType->setParam('expires_in', 3600);
$response = $tokenType->generateResponse();
$this->assertEquals($accessToken->getId(), $response['access_token']);
$this->assertEquals('mac', $response['token_type']);
$this->assertEquals(3600, $response['expires_in']);
$this->assertEquals('hmac-sha-256', $response['mac_algorithm']);
$this->assertArrayHasKey('mac_key', $response);
}
public function testDetermineAccessTokenInHeaderValid()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time();
$request = Request::createFromGlobals();
$calculatedSignatureParts = [
$ts,
'foo',
strtoupper($request->getMethod()),
$request->getRequestUri(),
$request->getHost(),
$request->getPort(),
'ext'
];
$calculatedSignature = base64_encode(hash_hmac('sha256', implode("\n", $calculatedSignatureParts), 'abcdef', true));
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, $calculatedSignature));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals('foo', $response);
}
public function testDetermineAccessTokenInHeaderMissingHeader()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMissingAuthMac()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$request->headers->set('Authorization', '');
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderInvalidParam()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$request = Request::createFromGlobals();
$request->headers->set('Authorization', 'MAC ');
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMismatchTimestamp()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn('abcdef');
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time() - 100;
$request = Request::createFromGlobals();
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, 'foo'));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
public function testDetermineAccessTokenInHeaderMissingMacKey()
{
$macStorage = M::mock('\League\OAuth2\Server\Storage\MacTokenInterface');
$macStorage->shouldReceive('getByAccessToken')->andReturn(null);
$server = new AuthorizationServer();
$server->setMacStorage($macStorage);
$ts = time();
$request = Request::createFromGlobals();
$request->headers->set('Authorization', sprintf('MAC id="foo", nonce="foo", ts="%s", mac="%s", ext="ext"', $ts, 'foo'));
$tokenType = new MAC();
$tokenType->setServer($server);
$response = $tokenType->determineAccessTokenInHeader($request);
$this->assertEquals(null, $response);
}
}

View File

@@ -8,9 +8,9 @@ class RedirectUriTest extends \PHPUnit_Framework_TestCase
{
public function testMake()
{
$v1 = RedirectUri::make('https://foobar/', array('foo'=>'bar'));
$v2 = RedirectUri::make('https://foobar/', array('foo'=>'bar'), '#');
$v3 = RedirectUri::make('https://foobar/', array('foo'=>'bar', 'bar' => 'foo'));
$v1 = RedirectUri::make('https://foobar/', ['foo' => 'bar']);
$v2 = RedirectUri::make('https://foobar/', ['foo' => 'bar'], '#');
$v3 = RedirectUri::make('https://foobar/', ['foo' => 'bar', 'bar' => 'foo']);
$this->assertEquals('https://foobar/?foo=bar', $v1);
$this->assertEquals('https://foobar/#foo=bar', $v2);

View File

@@ -2,7 +2,7 @@
namespace LeagueTests\util;
use \League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Util\SecureKey;
class SecureKeyTest extends \PHPUnit_Framework_TestCase
{
@@ -26,8 +26,7 @@ class SecureKeyTest extends \PHPUnit_Framework_TestCase
->expects($this->once())
->method('generate')
->with(11)
->will($this->returnValue($result))
;
->will($this->returnValue($result));
SecureKey::setAlgorithm($algorithm);
$this->assertSame($algorithm, SecureKey::getAlgorithm());