Compare commits

...

215 Commits
1.0.8 ... 2.1

Author SHA1 Message Date
Alex Bilbie
5d0b295a82 Merge branch 'release/2.1' 2013-05-10 17:59:29 -07:00
Alex Bilbie
9ec5442f90 Updated changelog 2013-05-10 17:59:08 -07:00
Alex Bilbie
4112913813 Version bump 2013-05-10 17:58:57 -07:00
Alex Bilbie
5eb4227709 Merge branch 'feature/auth-code-scopes' into develop. Fixes #44 2013-05-10 17:42:05 -07:00
Alex Bilbie
f5251a6080 Updated sessions 2013-05-10 17:39:29 -07:00
Alex Bilbie
86fb02d218 Added cascading relationship between oauth_sessions_authcodes and oauth_sessions 2013-05-10 17:32:39 -07:00
Alex Bilbie
ef4a138237 Fixed associateAuthCodeScope() query 2013-05-10 17:29:28 -07:00
Alex Bilbie
d531a37412 Don't add scope IDs 2013-05-10 17:26:23 -07:00
Alex Bilbie
ca599437f6 Added oauth_session_authcode_scopes 2013-05-10 17:24:46 -07:00
Alex Bilbie
252afddbd3 Updated oauth_session_authcodes table. Added id field, remove scope_ids field 2013-05-10 17:24:31 -07:00
Alex Bilbie
c57c4b1b4f Fixed key name 2013-05-10 17:19:53 -07:00
Alex Bilbie
ba2dc90f3b Altered associateScope logic 2013-05-10 17:08:20 -07:00
Alex Bilbie
7373f312da Updated variable name 2013-05-10 17:08:10 -07:00
Alex Bilbie
a01810d8fa Updated validateAuthCode in PDO Session 2013-05-10 17:07:29 -07:00
Alex Bilbie
3ea3eb5ebd Implemented getAuthCodeScopes() in PDO Session 2013-05-10 17:07:06 -07:00
Alex Bilbie
11022e16ef Updated validateAuthCode() in SessionInterface 2013-05-10 17:06:44 -07:00
Alex Bilbie
8d06a7b685 Updated getAuthCodeScopes() in SessionInterface 2013-05-10 17:06:05 -07:00
Alex Bilbie
c66c8092f9 Revert "Return the session_id for validateAuthCode instead of an array"
This reverts commit 51138f8738.
2013-05-10 16:57:39 -07:00
Alex Bilbie
591139f44d Added associateAuthCodeScope to PDO 2013-05-10 16:57:18 -07:00
Alex Bilbie
410ad09b5c Updated PDO associateAuthCode 2013-05-10 16:56:38 -07:00
Alex Bilbie
51138f8738 Return the session_id for validateAuthCode instead of an array 2013-05-10 16:53:52 -07:00
Alex Bilbie
aa8d38108f Associate scopes to auth codes in separate method. Creating an auth code now returns an ID 2013-05-10 16:53:21 -07:00
Alex Bilbie
9372cc85d0 Added getAuthCodeScopes() method 2013-05-10 16:50:34 -07:00
Alex Bilbie
accb80289f Added associateAuthCodeScope() method 2013-05-10 16:50:13 -07:00
Alex Bilbie
e591fbb25c Merge branch 'feature/refresh-token-rotation' into develop 2013-05-10 16:13:22 -07:00
Alex Bilbie
fdb89fb5e4 Updated tests 2013-05-10 16:13:11 -07:00
Alex Bilbie
ce51821043 If rotateRefreshTokens() is true then associate new access tokens 2013-05-10 16:13:06 -07:00
Alex Bilbie
eac33d50b3 Added missing semicolon 2013-05-10 16:12:43 -07:00
Alex Bilbie
2552b73b17 Added rotateRefreshTokens() method 2013-05-10 16:00:40 -07:00
Alex Bilbie
8c4019693b Updated @ziege's patch to overcome awkward access token definition requirement (i.e. access token can have a space in it) and also optimised code. Fixes #52 2013-05-10 12:57:34 -07:00
ziege
b88ef82563 Fixed two probems in access token check
1) The method returned the wrong result in case when the access token itself contained the string "Bearer".

2) When using cURL, the request is sometimes send twice (in my case when the first request returned a 404 error), and the Authorization header of the second request is doubled, so that you get a "Authorization: Bearer XXX, Bearer XXX". This case is checked now. (BTW: Tested with the current PHP version 5.4.15 on Windows.)
2013-05-10 20:00:01 +02:00
Alex Bilbie
3e5b4a1735 Move zetacomponents/database to "suggest" in composer.json. Fixes #51 2013-05-10 10:13:17 -07:00
Alex Bilbie
41a7125370 Accidentally used PHP 5.4 style bracket 2013-05-09 11:48:21 -07:00
Alex Bilbie
c40484abb1 Merge branch 'feature/refresh-token-rewrite' into develop 2013-05-09 11:42:31 -07:00
Alex Bilbie
f4bcfee687 Update associated scopes if requested in refresh access token. Fixes #47 2013-05-09 11:42:28 -07:00
Alex Bilbie
6d8eb9d05e Added removeRefreshToken method to SessionInterface 2013-05-09 11:40:29 -07:00
Alex Bilbie
76f2f6a5e1 Don't delete old sessions when issuing new access tokens using the Password or Client Credential grants. Fixes #32 2013-05-09 10:43:44 -07:00
Alex Bilbie
d677b765b2 Renamed scopes.key to scopes.scope. Updated ScopeInterface and PDO/Scope. Fixes #45 2013-05-09 10:23:41 -07:00
Alex Bilbie
7035792325 Allow for multiple default scopes. Fixes #42 2013-05-09 10:15:36 -07:00
Alex Bilbie
351c2e97ea If scope parameter is required and there are not requested scopes AND there is no default scope set then fail
Should have been included in with previous commit
2013-05-09 10:06:44 -07:00
Alex Bilbie
ddefb2ee16 Set the scope parameter to not be required by default. Fixes #43 2013-05-09 10:02:41 -07:00
Alex Bilbie
c3b41a5e8a Merge branch 'release/2.0.5' into develop 2013-05-09 09:47:33 -07:00
Alex Bilbie
b16c58bfe1 mErge branch 'release/2.0.5' 2013-05-09 09:47:21 -07:00
Alex Bilbie
e6d0a19e8f Version bump 2013-05-09 09:47:11 -07:00
Alex Bilbie
2296d09e92 Changelog update 2013-05-09 09:47:07 -07:00
Alex Bilbie
69af252844 Fixed docblock 2013-05-09 09:45:10 -07:00
Alex Bilbie
d9c598af3c Removed DEFAULT '' that has slipped in 2013-05-09 09:38:08 -07:00
Alex Bilbie
3cb79fc2b5 Fixed oauth_session_token_scopes primary key 2013-05-09 09:31:05 -07:00
Alex Bilbie
39379fe5b6 Merge branch 'release/2.0.4' into develop 2013-05-09 08:01:45 -07:00
Alex Bilbie
1375f91e15 Merge branch 'release/2.0.4' 2013-05-09 08:01:33 -07:00
Alex Bilbie
08a7055679 Version bump 2013-05-09 08:01:25 -07:00
Alex Bilbie
9f9a828294 Updated changelog 2013-05-09 08:01:18 -07:00
Alex Bilbie
77fbb2a851 Removed docblocks from session PDO class 2013-05-09 07:55:54 -07:00
Alex Bilbie
c0683586e2 A refresh token should be bound to a client ID 2013-05-09 07:55:10 -07:00
Alex Bilbie
86a483f288 Adding missing column to oauth_session_authcodes 2013-05-09 07:54:09 -07:00
Alex Bilbie
3617a3b37d Renamed primary key in oauth_client_endpoints table 2013-05-09 07:17:41 -07:00
Alex Bilbie
24634aabd7 Merge branch 'release/2.0.3' into develop 2013-05-08 22:09:35 -07:00
Alex Bilbie
ffc286c9f9 mErge branch 'release/2.0.3' 2013-05-08 22:09:18 -07:00
Alex Bilbie
7064442a4c Version bump 2013-05-08 22:09:10 -07:00
Alex Bilbie
68a64e9498 Fixed home page 2013-05-08 22:08:43 -07:00
Alex Bilbie
b04240b9e7 Merge branch 'release/2.0.2' into develop 2013-05-08 19:39:41 -07:00
Alex Bilbie
196a5aea13 Merge branch 'release/2.0.2' 2013-05-08 19:39:28 -07:00
Alex Bilbie
f2f99b429f Version bump 2013-05-08 19:39:15 -07:00
Alex Bilbie
561bda71a9 Link to wiki 2013-05-08 19:38:23 -07:00
Alex Bilbie
6b686a96e7 Updated tutorial links 2013-05-08 19:37:19 -07:00
Alex Bilbie
dbe21cc5a7 Removed null as default for parameters 2013-05-08 19:36:00 -07:00
Alex Bilbie
8b154054c3 Updated License 2013-05-08 19:04:40 -07:00
Alex Bilbie
972e517280 Added example queries and expected responses 2013-05-08 18:37:34 -07:00
Alex Bilbie
ca9760cd36 Updated docblocks and example queries in scope and client storage interfaces 2013-05-08 18:16:24 -07:00
Alex Bilbie
75894fd5bc Test for getClientId 2013-05-08 18:12:18 -07:00
Alex Bilbie
083a44df2e Fixed broken tests following previous commits 2013-05-08 18:10:43 -07:00
Alex Bilbie
1e57533127 Added getClientId method 2013-05-08 18:06:18 -07:00
Alex Bilbie
92e217d0ac Show default parameters 2013-05-08 18:06:09 -07:00
Alex Bilbie
707354348a Changed scope to be a delimiter to a space as required by the spec 2013-05-08 17:42:15 -07:00
Alex Bilbie
f0d493b064 Updated link to wiki 2013-05-08 17:04:17 -07:00
Alex Bilbie
46f0e6c84d Updated docblocks 2013-05-08 17:04:01 -07:00
Alex Bilbie
1dd768545a Updated more docblocks 2013-05-08 14:10:58 -07:00
Alex Bilbie
787c8c566f Updated docblocks 2013-05-08 14:10:48 -07:00
Alex Bilbie
fd10861065 Added missing docblock 2013-05-08 14:10:15 -07:00
Alex Bilbie
0812ca2927 Added missing clientId variable, fixed docblock 2013-05-08 13:59:17 -07:00
Alex Bilbie
a8a375ed1f Anal code style fix 2013-05-08 13:40:15 -07:00
Alex Bilbie
f4b32a2bc6 Optimised tests by removing unused variables and adding further assertions 2013-05-08 13:34:05 -07:00
Alex Bilbie
e2350a65b1 Removed unused functions 2013-05-08 13:24:29 -07:00
Alex Bilbie
437833cd32 Renamed AuthServer to Authorization, renamed ResourceServer to Resource. Updated all tests and other files 2013-05-08 11:42:23 -07:00
Alex Bilbie
1df524ae6e Added missing docblocks 2013-05-08 11:31:38 -07:00
Alex Bilbie
9d1693cf78 Fixed incorrect @link 2013-05-08 11:30:53 -07:00
Alex Bilbie
5524e9b9c8 Moved files into server namespace/folder and updated docblock copyright statements 2013-05-08 11:29:24 -07:00
Alex Bilbie
2d6cc3c98e Renamed package 2013-05-08 11:06:49 -07:00
Alex Bilbie
f4b955ccff Updated tests for new namespace 2013-05-08 11:06:21 -07:00
Alex Bilbie
850473ce40 Renamed namespace to League\OAuth2\ 2013-05-08 11:06:09 -07:00
Alex Bilbie
22d900def1 Updated the changelog 2013-05-08 10:52:13 -07:00
Alex Bilbie
41eef0c3e2 Updated the README 2013-05-08 10:51:56 -07:00
Alex Bilbie
037fd6e4f7 Test for setRefreshTokenTTL 2013-05-08 10:44:03 -07:00
Alex Bilbie
0b927ddfbb Test for setAuthTokenTTL 2013-05-08 10:43:53 -07:00
Alex Bilbie
56b8b7c64e Updated associateRefreshToken to use expire time 2013-05-08 10:38:16 -07:00
Alex Bilbie
0407dbb09b Added refresh token expires column 2013-05-08 10:35:24 -07:00
Alex Bilbie
d6932cbb5e Renamed get/setExpiresIn to get/setAccessTokenTTL 2013-05-08 10:35:13 -07:00
Alex Bilbie
c77484e97b Added refresh token TTL 2013-05-08 10:34:25 -07:00
Alex Bilbie
9f90cd2635 Added method to set the auth token TTL 2013-05-07 15:20:32 -07:00
Alex Bilbie
8fd9e3f312 Renamed setExpiresIn method to accessTokenTTL 2013-05-07 15:16:30 -07:00
Alex Bilbie
5df1338046 New test for getGrantType to test for exception 2013-05-06 15:42:11 -07:00
Alex Bilbie
5d7e0d67cc Updated tests for custom expires in 2013-05-06 15:36:59 -07:00
Alex Bilbie
fdebbac2df Allow grant access token expiresIn override 2013-05-06 15:04:00 -07:00
Alex Bilbie
a561a9d98a Throw an exception if a grant can't be loaded when called in getGrantType 2013-05-06 13:57:46 -07:00
Alex Bilbie
3ac6690ac9 Fixed repo url 2013-05-06 13:13:11 -07:00
Alex Bilbie
e1f83a50ae Merge branch 'refs/heads/develop'
Conflicts:
	composer.json
	src/OAuth2/AuthServer.php
	src/OAuth2/Grant/Password.php
2013-05-06 13:05:39 -07:00
Alex Bilbie
8cdc273dba Fixed composer.json replace key 2013-05-06 12:57:44 -07:00
Alex Bilbie
eada9053ad Updated README 2013-05-06 12:54:16 -07:00
Alex Bilbie
5867774bee Added "replace" key into composer.json 2013-05-06 12:53:39 -07:00
Alex Bilbie
18151d9a8e Version 2.0 baby! 2013-05-06 12:43:50 -07:00
Alex Bilbie
f207a1909f Updated package description 2013-05-06 12:43:38 -07:00
Alex Bilbie
e713d0df9c Renamed package 2013-05-06 12:43:27 -07:00
Alex Bilbie
1ca8a4f4c3 Updated authserver tests 2013-05-06 11:09:36 -07:00
Alex Bilbie
9349425ecd Fixed ResourceServerTest.php 2013-05-06 10:28:49 -07:00
Alex Bilbie
38f6be2aa0 Removed unnecessary methods 2013-05-05 18:22:03 +01:00
Alex Bilbie
d0abd8c295 Fixed getting of session scopes 2013-05-05 18:18:55 +01:00
Alex Bilbie
9be23cf222 Added session scopes 2013-05-05 18:16:28 +01:00
Alex Bilbie
90508a191d Get scopes by access token instead of session ID 2013-05-05 18:14:27 +01:00
Alex Bilbie
10d7d3cb3d Updated response params 2013-05-05 18:11:01 +01:00
Alex Bilbie
89850420f6 Updated query to return session details 2013-05-05 18:09:47 +01:00
Alex Bilbie
9b73eab07c SQL query fix 2013-05-05 18:06:00 +01:00
Alex Bilbie
6897e233d4 Changed variable syntax style to be PSR2 2013-05-05 18:05:46 +01:00
Alex Bilbie
acfadc8993 Actually fixed the bug in validateAccessToken this time 2013-05-05 18:01:00 +01:00
Alex Bilbie
cc81e20206 Bug fix in validateAccessToken 2013-05-05 18:00:08 +01:00
Alex Bilbie
92303c7b26 Implemented validateAccessToken in PDO 2013-05-05 17:58:40 +01:00
Alex Bilbie
2866185349 Updated implicit grant 2013-04-30 15:51:55 +01:00
Alex Bilbie
b9570ac6b0 Fixed getScopes 2013-04-30 15:48:11 +01:00
Alex Bilbie
2a3ae641ab Added getAccessToken, fixed validateRefreshToken docblock 2013-04-30 15:38:48 +01:00
Alex Bilbie
d149490c78 Updated getScopes 2013-04-30 15:32:07 +01:00
Alex Bilbie
c0d8a2c4fb Lots of updated functions 2013-04-30 15:08:20 +01:00
Alex Bilbie
5b03859467 Removed unnecessary code 2013-04-30 15:08:03 +01:00
Alex Bilbie
a661634194 Updated refresh token grant 2013-04-30 15:07:44 +01:00
Alex Bilbie
c73d45fc07 PSR-2 fix 2013-04-30 14:33:30 +01:00
Alex Bilbie
85a53d7470 Fixed Password grant to match past updates 2013-04-30 14:28:59 +01:00
Alex Bilbie
18eea191ed Fixed docblock 2013-04-30 14:28:40 +01:00
Alex Bilbie
14cff9ea44 Added missing db init 2013-04-29 11:59:45 +01:00
Alex Bilbie
1696903b8b Removed extra bracket 2013-04-29 11:53:20 +01:00
Alex Bilbie
13c67c9a40 Updated completeFlow 2013-04-29 11:31:07 +01:00
Alex Bilbie
2dcb81d93c Updated newAuthoriseRequest 2013-04-29 11:25:23 +01:00
Alex Bilbie
b39a9a5edc Added missing DB instance::get() calls 2013-04-29 11:13:31 +01:00
Alex Bilbie
325242e3aa Added missing third parameter 2013-04-29 11:12:35 +01:00
Alex Bilbie
757d2a4fd9 Removed scalar type hinting because it isn't supported 2013-04-29 11:11:16 +01:00
Alex Bilbie
725ab74e5c Updated PDO session 2013-04-29 11:02:32 +01:00
Alex Bilbie
b7ca5d330b Updated associateRefreshToken 2013-04-29 11:02:03 +01:00
Alex Bilbie
4034bea6d1 Updated client credentials grant 2013-04-29 10:36:35 +01:00
Alex Bilbie
6751c4d2fe Fixed mistake from previous commit 2013-04-29 10:35:47 +01:00
Alex Bilbie
53a55d4946 Completely scrapped the old SessionInterface and simplified it 2013-04-29 10:34:11 +01:00
Alex Bilbie
79338d0d75 Delete an associated auth code 2013-04-29 00:02:00 +01:00
Alex Bilbie
17bc6a1512 Comment update 2013-04-29 00:01:51 +01:00
Alex Bilbie
6543ebcd4d Updated updateSession code 2013-04-29 00:01:34 +01:00
Alex Bilbie
351bec6019 Don't associate a scope with a session, we associate it with an access token later 2013-04-29 00:01:07 +01:00
Alex Bilbie
a4715bfc3b Updated create a new session 2013-04-29 00:00:04 +01:00
Alex Bilbie
4ef8030a93 First commit of PDO storage class 2013-04-28 23:58:01 +01:00
Alex Bilbie
7bfbe81f61 Started PDO storage classes 2013-04-28 23:57:50 +01:00
Alex Bilbie
81d6bcf00a Changed params around and removed line breaks 2013-04-28 23:57:29 +01:00
Alex Bilbie
a93a039df3 Lots of table fixes 2013-04-28 23:56:17 +01:00
Alex Bilbie
d0d0d2a7c3 Require zetacompontents/database 2013-04-28 19:06:21 +01:00
Alex Bilbie
6f71439edd Renamed lots of columns 2013-04-23 14:20:38 +01:00
Alex Bilbie
b0d3ba7e70 Revert "Removed session_token_id column from oauth_session_authcode"
This reverts commit 859e6720bf.
2013-04-23 13:56:13 +01:00
Alex Bilbie
a265b027cc Removed stage parameter 2013-04-23 13:52:21 +01:00
Alex Bilbie
859e6720bf Removed session_token_id column from oauth_session_authcode 2013-04-23 13:45:07 +01:00
Alex Bilbie
b7bae1120b Fixed mysql character set 2013-04-23 13:44:21 +01:00
Alex Bilbie
4727a83d84 Removed stage parameter 2013-04-23 13:29:33 +01:00
Alex Bilbie
67641acdff Revert "renamed package to oauth2-server"
This reverts commit 09b74aa61d.
2013-04-17 14:27:09 +01:00
Alex Bilbie
09b74aa61d renamed package to oauth2-server 2013-04-17 14:22:42 +01:00
Alex Bilbie
d75d266376 Updated SQL structure 2013-04-03 15:50:07 +01:00
Alex Bilbie
645d412c02 Removed die(var_dump()) 2013-03-31 13:57:35 +01:00
Alex Bilbie
5f1609577e Added stateParamRequired method 2013-03-31 13:57:24 +01:00
Alex Bilbie
351580d9d8 Added getResponseTypes() method 2013-03-31 13:37:12 +01:00
Alex Bilbie
9c9db978c6 Move authorisation code grant stuff into own grant 2013-03-31 13:37:02 +01:00
Alex Bilbie
a18b4184f5 getScopes() now have the grant type and client ID passed 2013-03-28 10:44:45 +00:00
Alex Bilbie
a7b4f7d66b Added grant to getClient calls. Fixes #21 2013-03-27 14:47:07 +00:00
Alex Bilbie
18933d5075 Merge branch 'feature/http-headers' into develop. Fixes #29 2013-03-27 14:27:47 +00:00
Alex Bilbie
d53abc661c getExceptionHttpHeaders() unit tests 2013-03-27 14:27:06 +00:00
Alex Bilbie
3481ec8aa2 Variable name fixes + little changes to support unit tests 2013-03-27 14:26:46 +00:00
ziege
e563230f10 Method to get all headers for the error response
Method added to get all required headers for the error response, according to the RFC - the correct HTTP status code and the "WWW-Authenticate" header in special cases.
2013-03-27 13:33:09 +00:00
Alex Bilbie
28f85e3bea Fixed broken unit test. Fixes #28 2013-03-27 13:29:11 +00:00
ziege
4cb4d5ba21 Refresh token removed in Client Credentials Grant
As defined in RFC: http://tools.ietf.org/html/rfc6749#section-4.4.3
2013-03-27 13:25:58 +00:00
Alex Bilbie
be478561b6 Fixed unit tests following 74d9946db3 2013-03-22 16:28:45 +00:00
Alex Bilbie
608fdb3ac3 Merge pull request #26 from ziege/patch-1
Storage corrected
2013-03-22 09:27:14 -07:00
ziege
74d9946db3 Storage corrected
Wrong client storage replaced with session storage
2013-03-22 17:24:36 +01:00
Alex Bilbie
521e5b22aa Updated unit tests 2013-03-22 12:43:53 +00:00
Alex Bilbie
85312f6995 Updated ClientCredentials to properly include scopes 2013-03-22 12:36:18 +00:00
Alex Bilbie
f463eb9db1 Style fixes 2013-03-22 11:44:53 +00:00
Alex Bilbie
f4cdfa91c1 Updated Password grant 2013-03-22 11:41:04 +00:00
Alex Bilbie
fe6ecb1dcf Added test_issueAccessToken_HTTP_auth(). Fixes #22 2013-03-22 11:08:52 +00:00
Alex Bilbie
0bf2a5333a Added test_scopeParamRequired() 2013-03-22 11:07:55 +00:00
Alex Bilbie
105a5b2a31 Fixed client_id and client_secret retrieval from request in conformity with the RFC 2013-03-22 10:40:47 +00:00
Alex Bilbie
ecf2f2b9ea Updated ResourceServerTest 2013-03-22 10:37:01 +00:00
Alex Bilbie
493834fcbf Removed base64 decoding of token when present in authorization header. Fixes #23 2013-03-22 10:35:42 +00:00
Alex Bilbie
fb518715ce Updated authserver tests 2013-03-21 16:25:44 +00:00
Alex Bilbie
fce24aa74d Added getDefaultScope method 2013-03-21 16:22:44 +00:00
Alex Bilbie
0c30b9ca66 Added scopeParamRequired method 2013-03-21 16:22:29 +00:00
Alex Bilbie
03aa81450e Renamed method to setDefaultScope 2013-03-21 16:22:16 +00:00
Michael Gooden
6c34535155 First test case.
Signed-off-by: Michael Gooden <michael@bluepointweb.com>
2013-03-21 14:47:32 +00:00
Michael Gooden
5bd62fe942 Add optional default scope parameter.
Signed-off-by: Michael Gooden <me@michaelgooden.net>
2013-03-21 14:47:29 +00:00
lapause
26781d2c38 Corrected wrong return documentation for SessionInterface::validateAuthCode() method 2013-03-21 14:42:51 +00:00
lapause
18e1bb33de Added missing details (return values on failure) to methods of SessionInterface 2013-03-21 14:42:47 +00:00
lapause
3a6468897f Removed obsolete namespace inclusion 2013-03-21 14:42:43 +00:00
lapause
97484eea6a Typo correction in inline doc 2013-03-21 14:42:38 +00:00
Alex Bilbie
3341728eb2 Added implicit grant 2013-03-06 18:01:44 +00:00
Alex Bilbie
6b172d4c27 Made getGrantType public for use with implicit grant 2013-03-06 18:01:34 +00:00
Alex Bilbie
4962762c28 Change from static calls 2013-03-06 18:01:12 +00:00
Alex Bilbie
56b559894c Spelling fix 2013-03-06 17:57:48 +00:00
Alex Bilbie
a9a68a5cc8 Added scope parameter association for clientcredentials and password scope
TODO: Unit tests
2013-03-06 17:18:48 +00:00
Alex Bilbie
542ca52d49 Set a default parameter for getParam 2013-03-06 17:18:13 +00:00
Alex Bilbie
7d0c075b36 It ain't static anymore Jim 2013-03-06 17:18:04 +00:00
Alex Bilbie
c056be3e48 Updated .travis.yml 2013-03-06 17:05:07 +00:00
Alex Bilbie
f3e6f99696 Removed old build files 2013-03-06 17:04:49 +00:00
Alex Bilbie
3ad4010526 Cleaned up .gitignore 2013-03-06 17:04:31 +00:00
Alex Bilbie
07c07ccb5e Removed static functions, inject authserver instance into grants 2013-03-06 16:59:18 +00:00
Alex Bilbie
6a8f8bf7b7 Removed phpunit from composer.json 2013-03-06 16:58:29 +00:00
Alex Bilbie
4917bc228c Updated .gitignore 2013-03-06 16:57:29 +00:00
Alex Bilbie
b58082b536 Merge pull request #10 from MichaelGooden/patch-1
Fix state parameter check typo
2013-03-04 07:43:33 -08:00
Michael Gooden
f70c039275 Fix state parameter check typo 2013-03-04 17:31:59 +02:00
49 changed files with 3768 additions and 1648 deletions

12
.gitignore vendored
View File

@@ -1,8 +1,6 @@
/vendor/
/vendor
/composer.lock
/docs/build/
/build/logs/
/build/coverage/
test
/docs/
/testing/
/build/logs
/build/coverage
/docs
/testing

View File

@@ -5,4 +5,4 @@ php:
- 5.4
before_script: composer install --dev
script: phpunit -c build/phpunit.xml
script: phpunit

View File

@@ -1,5 +1,51 @@
# Changelog
## 2.1 (released 2013-05-10)
* Moved zetacomponents/database to "suggest" in composer.json. If you rely on this feature you now need to include " zetacomponents/database" into "require" key in your own composer.json. (Issue #51)
* New method in Refresh grant called `rotateRefreshTokens()`. Pass in `true` to issue a new refresh token each time an access token is refreshed. This parameter needs to be set to true in order to request reduced scopes with the new access token. (Issue #47)
* Rename `key` column in oauth_scopes table to `scope` as `key` is a reserved SQL word. (Issue #45)
* The `scope` parameter is no longer required by default as per the RFC. (Issue #43)
* You can now set multiple default scopes by passing an array into `setDefaultScope()`. (Issue #42)
* The password and client credentials grants now allow for multiple sessions per user. (Issue #32)
* Scopes associated to authorization codes are not held in their own table (Issue #44)
* Database schema updates.
## 2.0.5 (released 2013-05-09)
* Fixed `oauth_session_token_scopes` table primary key
* Removed `DEFAULT ''` that has slipped into some tables
* Fixed docblock for `SessionInterface::associateRefreshToken()`
## 2.0.4 (released 2013-05-09)
* Renamed primary key in oauth_client_endpoints table
* Adding missing column to oauth_session_authcodes
* SECURITY FIX: A refresh token should be bound to a client ID
## 2.0.3 (released 2013-05-08)
* Fixed a link to code in composer.json
## 2.0.2 (released 2013-05-08)
* Updated README with wiki guides
* Removed `null` as default parameters in some methods in the storage interfaces
* Fixed license copyright
## 2.0.0 (released 2013-05-08)
**If you're upgrading from v1.0.8 there are lots of breaking changes**
* Rewrote the session storage interface from scratch so methods are more obvious
* Included a PDO driver which implements the storage interfaces so the library is more "get up and go"
* Further normalised the database structure so all sessions no longer contain infomation related to authorization grant (which may or may not be enabled)
* A session can have multiple associated access tokens
* Induvidual grants can have custom expire times for access tokens
* Authorization codes now have a TTL of 10 minutes by default (can be manually set)
* Refresh tokens now have a TTL of one week by default (can be manually set)
* The client credentials grant will no longer gives out refresh tokens as per the specification
## 1.0.8 (released 2013-03-18)
* Fixed check for required state parameter

View File

@@ -1,6 +1,6 @@
# PHP OAuth Framework
# The League of Extraordinary Packages presents: PHP OAuth 2.0 Server
The goal of this project is to develop a standards compliant [OAuth 2](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource server.
The goal of this project is to develop a standards compliant [OAuth 2.0](http://tools.ietf.org/wg/oauth/draft-ietf-oauth-v2/) authorization server and resource server.
## Package Installation
@@ -9,38 +9,47 @@ The framework is provided as a Composer package which can be installed by adding
```javascript
{
"require": {
"lncd/OAuth2": "*"
"league/oauth2-server": "2.*"
}
}
```
---
The library features 100% unit test code coverage. To run the tests yourself run `phpunit -c build/phpunit.xml`.
The library features 100% unit test code coverage. To run the tests yourself run `phpunit` from the project root.
## Current Features
### Authorization Server
The authorization server is a flexible class and following core specification grants are implemented:
The authorization server is a flexible class and the following core specification grants are implemented:
* authorization code ([section 4.1](http://tools.ietf.org/html/rfc6749#section-4.1))
* refresh token ([section 6](http://tools.ietf.org/html/rfc6749#section-6))
* client credentials ([section 2.3.1](http://tools.ietf.org/html/rfc6749#section-2.3.1))
* password (user credentials) ([section 4.3](http://tools.ietf.org/html/rfc6749#section-4.3))
An overview of the different OAuth 2.0 grants can be found at [http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/](http://alexbilbie.com/2013/02/a-guide-to-oauth-2-grants/).
An overview of the different OAuth 2.0 grants can be found in the wiki [https://github.com/php-loep/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use%3F](https://github.com/php-loep/oauth2-server/wiki/Which-OAuth-2.0-grant-should-I-use%3F).
### Resource Server
The resource server allows you to secure your API endpoints by checking for a valid OAuth access token in the request and ensuring the token has the correct permission to access resources.
The resource server allows you to secure your API endpoints by checking for a valid OAuth access token in the request and ensuring the token has the correct scope(s) (i.e. permissions) to access resources.
### Custom grants
## Tutorials
Custom grants can be created easily by implementing an interface. Check out a guide here [https://github.com/php-loep/oauth2-server/wiki/Creating-custom-grants](https://github.com/php-loep/oauth2-server/wiki/Creating-custom-grants).
A tutorial on how to use the authorization server can be found at [http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/](http://alexbilbie.com/2013/02/developing-an-oauth2-authorization-server/).
### PDO driver
A tutorial on how to use the resource server to secure an API server can be found at [http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/](http://alexbilbie.com/2013/02/securing-your-api-with-oauth-2/).
If you are using MySQL and want to very quickly implement the library then all of the storage interfaces have been implemented with PDO classes. Check out the guide here [https://github.com/php-loep/oauth2-server/wiki/Using-the-PDO-storage-classes](https://github.com/php-loep/oauth2-server/wiki/Using-the-PDO-storage-classes).
## Tutorials and documentation
The wiki has lots of guides on how to use this library, check it out - [https://github.com/php-loep/oauth2-server/wiki](https://github.com/php-loep/oauth2-server/wiki).
A tutorial on how to use the authorization server can be found on the wiki - (https://github.com/php-loep/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server)[https://github.com/php-loep/oauth2-server/wiki/Developing-an-OAuth-2.0-authorization-server].
A tutorial on how to use the resource server to secure an API server can be found at [https://github.com/php-loep/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0](https://github.com/php-loep/oauth2-server/wiki/Securing-your-API-with-OAuth-2.0).
## Future Goals
@@ -51,11 +60,8 @@ A tutorial on how to use the resource server to secure an API server can be foun
---
This code will be developed as part of the [Linkey](http://linkey.blogs.lincoln.ac.uk) project which has been funded by [JISC](http://jisc.ac.uk) under the Access and Identity Management programme.
The initial code was developed as part of the [Linkey](http://linkey.blogs.lincoln.ac.uk) project which was funded by [JISC](http://jisc.ac.uk) under the Access and Identity Management programme.
This code was principally developed by [Alex Bilbie](http://alexbilbie.com/) ([Twitter](https://twitter.com/alexbilbie)|[Github](https://github.com/alexbilbie)).
This code is principally developed and maintained by [@alexbilbie](https://twitter.com/alexbilbie).
Valuable contribtions have been made by the following:
* [Dan Horrigan](http://dandoescode.com) ([Twitter](https://twitter.com/dandoescode)|[Github](https://github.com/dandoescode))
* [Nick Jackson](http://nickjackson.me) ([Twitter](https://twitter.com/jacksonj04)|[Github](https://github.com/jacksonj04))
A list of contributors can be found at [https://github.com/php-loep/oauth2-server/contributors](https://github.com/php-loep/oauth2-server/contributors).

View File

@@ -1,8 +0,0 @@
<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
<description>PHP_CodeSniffer configuration</description>
<rule ref="PSR2"/>
</ruleset>

View File

@@ -1,14 +0,0 @@
<ruleset name="OAuth 2.0 Server"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0
http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>
Ruleset for OAuth 2.0 server
</description>
<!-- Import the entire unused code rule set -->
<rule ref="rulesets/unusedcode.xml" />
</ruleset>

View File

@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="../tests/Bootstrap.php">
<testsuites>
<testsuite name="Authorization Server">
<directory suffix="Test.php">../tests/authorization</directory>
</testsuite>
<testsuite name="Resource Server">
<directory suffix="Test.php">../tests/resource</directory>
</testsuite>
<testsuite name="Utility Methods">
<directory suffix="Test.php">../tests/util</directory>
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">../vendor/composer</directory>
<directory suffix=".php">../vendor/mockery</directory>
<directory suffix=".php">../vendor/phpunit</directory>
<directory suffix=".php">../tests</directory>
<directory suffix=".php">../testing</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-html" target="coverage" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-text" target="php://stdout" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-clover" target="logs/clover.xml"/>
<log type="junit" target="logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>

View File

@@ -1,20 +1,19 @@
{
"name": "lncd/oauth2",
"description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants",
"version": "1.0.8",
"homepage": "https://github.com/lncd/OAuth2",
"name": "league/oauth2-server",
"description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.",
"version": "2.1",
"homepage": "https://github.com/php-loep/oauth2-server",
"license": "MIT",
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "*",
"mockery/mockery": ">=0.7.2"
"mockery/mockery": ">=0.7.2"
},
"repositories": [
{
"type": "git",
"url": "https://github.com/lncd/OAuth2"
"url": "https://github.com/php-loep/oauth2-server.git"
}
],
"keywords": [
@@ -34,10 +33,16 @@
"role": "Developer"
}
],
"replace": {
"lncd/oauth2": "*",
"league/oauth2server": "*"
},
"autoload": {
"psr-0": {
"OAuth2": "src/"
"League\\OAuth2\\Server": "src/"
}
},
"suggest": {}
}
"suggest": {
"zetacomponents/database": "Allows use of the build in PDO storage classes"
}
}

View File

@@ -1,20 +1,20 @@
MIT License
Copyright (C) 2012 University of Lincoln
Copyright (C) 2013 PHP League of Extraordinary Packages
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

31
phpunit.xml Normal file
View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" bootstrap="tests/Bootstrap.php">
<testsuites>
<testsuite name="Authorization Server">
<directory suffix="Test.php">tests/authorization</directory>
</testsuite>
<testsuite name="Resource Server">
<directory suffix="Test.php">tests/resource</directory>
</testsuite>
<testsuite name="Utility Methods">
<directory suffix="Test.php">tests/util</directory>
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory suffix=".php">PEAR_INSTALL_DIR</directory>
<directory suffix=".php">PHP_LIBDIR</directory>
<directory suffix=".php">vendor/composer</directory>
<directory suffix=".php">vendor/mockery</directory>
<directory suffix=".php">vendor/phpunit</directory>
<directory suffix=".php">tests</directory>
<directory suffix=".php">testing</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-html" target="build/coverage" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-text" target="php://stdout" title="lncd/OAuth" charset="UTF-8" yui="true" highlight="true" lowUpperBound="50" highLowerBound="90"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>

View File

@@ -1,53 +1,95 @@
CREATE TABLE `oauth_clients` (
`id` varchar(40) NOT NULL DEFAULT '',
`secret` varchar(40) NOT NULL DEFAULT '',
`name` varchar(255) NOT NULL DEFAULT '',
`auto_approve` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`id` CHAR(40) NOT NULL,
`secret` CHAR(40) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`auto_approve` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `u_oacl_clse_clid` (`secret`,`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_client_endpoints` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client_id` varchar(40) NOT NULL DEFAULT '',
`redirect_uri` varchar(255) DEFAULT NULL,
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`client_id` char(40) NOT NULL,
`redirect_uri` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `client_id` (`client_id`),
CONSTRAINT `oauth_client_endpoints_ibfk_1` FOREIGN KEY (`client_id`) REFERENCES `oauth_clients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
KEY `i_oaclen_clid` (`client_id`),
CONSTRAINT `f_oaclen_clid` FOREIGN KEY (`client_id`) REFERENCES `oauth_clients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_sessions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client_id` varchar(40) NOT NULL DEFAULT '',
`redirect_uri` varchar(250) DEFAULT '',
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`client_id` char(40) NOT NULL,
`owner_type` enum('user','client') NOT NULL DEFAULT 'user',
`owner_id` varchar(255) DEFAULT '',
`auth_code` varchar(40) DEFAULT '',
`access_token` varchar(40) DEFAULT '',
`refresh_token` varchar(40) DEFAULT '',
`access_token_expires` int(10) DEFAULT NULL,
`stage` enum('requested','granted') NOT NULL DEFAULT 'requested',
`first_requested` int(10) unsigned NOT NULL,
`last_updated` int(10) unsigned NOT NULL,
`owner_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `client_id` (`client_id`)
KEY `i_uase_clid_owty_owid` (`client_id`,`owner_type`,`owner_id`),
CONSTRAINT `f_oase_clid` FOREIGN KEY (`client_id`) REFERENCES `oauth_clients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_access_tokens` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`session_id` int(10) unsigned NOT NULL,
`access_token` char(40) NOT NULL,
`access_token_expires` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u_oaseacto_acto_seid` (`access_token`,`session_id`),
KEY `f_oaseto_seid` (`session_id`),
CONSTRAINT `f_oaseto_seid` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_authcodes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`session_id` int(10) unsigned NOT NULL,
`auth_code` char(40) NOT NULL,
`auth_code_expires` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `session_id` (`session_id`),
CONSTRAINT `oauth_session_authcodes_ibfk_1` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_redirects` (
`session_id` int(10) unsigned NOT NULL,
`redirect_uri` varchar(255) NOT NULL,
PRIMARY KEY (`session_id`),
CONSTRAINT `f_oasere_seid` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_refresh_tokens` (
`session_access_token_id` int(10) unsigned NOT NULL,
`refresh_token` char(40) NOT NULL,
`refresh_token_expires` int(10) unsigned NOT NULL,
`client_id` char(40) NOT NULL,
PRIMARY KEY (`session_access_token_id`),
KEY `client_id` (`client_id`),
CONSTRAINT `oauth_session_refresh_tokens_ibfk_1` FOREIGN KEY (`client_id`) REFERENCES `oauth_clients` (`id`) ON DELETE CASCADE,
CONSTRAINT `f_oasetore_setoid` FOREIGN KEY (`session_access_token_id`) REFERENCES `oauth_session_access_tokens` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_scopes` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`scope` varchar(255) NOT NULL DEFAULT '',
`name` varchar(255) NOT NULL DEFAULT '',
`description` varchar(255) DEFAULT '',
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`scope` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `scope` (`scope`)
UNIQUE KEY `u_oasc_sc` (`scope`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_scopes` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`session_id` int(11) unsigned NOT NULL,
`scope_id` int(11) unsigned NOT NULL,
CREATE TABLE `oauth_session_token_scopes` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`session_access_token_id` int(10) unsigned DEFAULT NULL,
`scope_id` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `session_id` (`session_id`),
UNIQUE KEY `u_setosc_setoid_scid` (`session_access_token_id`,`scope_id`),
KEY `f_oasetosc_scid` (`scope_id`),
CONSTRAINT `f_oasetosc_scid` FOREIGN KEY (`scope_id`) REFERENCES `oauth_scopes` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `f_oasetosc_setoid` FOREIGN KEY (`session_access_token_id`) REFERENCES `oauth_session_access_tokens` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_session_authcode_scopes` (
`oauth_session_authcode_id` int(10) unsigned NOT NULL,
`scope_id` smallint(5) unsigned NOT NULL,
KEY `oauth_session_authcode_id` (`oauth_session_authcode_id`),
KEY `scope_id` (`scope_id`),
CONSTRAINT `oauth_session_scopes_ibfk_5` FOREIGN KEY (`scope_id`) REFERENCES `oauth_scopes` (`id`) ON DELETE CASCADE,
CONSTRAINT `oauth_session_scopes_ibfk_4` FOREIGN KEY (`session_id`) REFERENCES `oauth_sessions` (`id`) ON DELETE CASCADE
CONSTRAINT `oauth_session_authcode_scopes_ibfk_2` FOREIGN KEY (`scope_id`) REFERENCES `oauth_scopes` (`id`) ON DELETE CASCADE,
CONSTRAINT `oauth_session_authcode_scopes_ibfk_1` FOREIGN KEY (`oauth_session_authcode_id`) REFERENCES `oauth_session_authcodes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@@ -2,42 +2,40 @@
/**
* OAuth 2.0 Authorization Server
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2;
namespace League\OAuth2\Server;
use OAuth2\Util\Request;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
use OAuth2\Grant\GrantTypeInterface;
use League\OAuth2\Server\Util\Request;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
use League\OAuth2\Server\Grant\GrantTypeInterface;
/**
* OAuth 2.0 authorization server class
*/
class AuthServer
class Authorization
{
/**
* The delimeter between scopes specified in the scope query string parameter
*
* The OAuth 2 specification states it should be a space but that is stupid
* and everyone excepted Google use a comma instead.
*
* The OAuth 2 specification states it should be a space but most use a comma
* @var string
*/
protected $scopeDelimeter = ',';
protected $scopeDelimeter = ' ';
/**
* The TTL (time to live) of an access token in seconds (default: 3600)
* @var integer
*/
static protected $expiresIn = 3600;
protected $accessTokenTTL = 3600;
/**
* The registered grant response types
@@ -49,19 +47,25 @@ class AuthServer
* The client, scope and session storage classes
* @var array
*/
static protected $storages = array();
protected $storages = array();
/**
* The registered grant types
* @var array
*/
static protected $grantTypes = array();
protected $grantTypes = array();
/**
* Require the "scope" parameter to be in checkAuthoriseParams()
* @var boolean
*/
protected $requireScopeParam = true;
protected $requireScopeParam = false;
/**
* Default scope(s) to be used if none is provided
* @var string|array
*/
protected $defaultScope = null;
/**
* Require the "state" parameter to be in checkAuthoriseParams()
@@ -73,7 +77,7 @@ class AuthServer
* The request object
* @var Util\RequestInterface
*/
static protected $request = null;
protected $request = null;
/**
* Exception error codes
@@ -96,7 +100,7 @@ class AuthServer
* Exception error messages
* @var array
*/
static protected $exceptionMessages = array(
protected static $exceptionMessages = array(
'invalid_request' => '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.',
'unauthorized_client' => 'The client is not authorized to request an access token using this method.',
'access_denied' => 'The resource owner or authorization server denied the request.',
@@ -111,6 +115,87 @@ class AuthServer
'invalid_refresh' => 'The refresh token is invalid.',
);
/**
* Exception error HTTP status codes
* @var array
*
* RFC 6749, section 4.1.2.1.:
* No 503 status code for 'temporarily_unavailable', because
* "a 503 Service Unavailable HTTP status code cannot be
* returned to the client via an HTTP redirect"
*/
protected static $exceptionHttpStatusCodes = array(
'invalid_request' => 400,
'unauthorized_client' => 400,
'access_denied' => 401,
'unsupported_response_type' => 400,
'invalid_scope' => 400,
'server_error' => 500,
'temporarily_unavailable' => 400,
'unsupported_grant_type' => 501,
'invalid_client' => 401,
'invalid_grant' => 400,
'invalid_credentials' => 400,
'invalid_refresh' => 400,
);
/**
* Get all headers that have to be send with the error response
*
* @param string $error The error message key
* @return array Array with header values
*/
public static function getExceptionHttpHeaders($error)
{
$headers = array();
switch (self::$exceptionHttpStatusCodes[$error]) {
case 401:
$headers[] = 'HTTP/1.1 401 Unauthorized';
break;
case 500:
$headers[] = 'HTTP/1.1 500 Internal Server Error';
break;
case 501:
$headers[] = 'HTTP/1.1 501 Not Implemented';
break;
case 400:
default:
$headers[] = 'HTTP/1.1 400 Bad Request';
}
// Add "WWW-Authenticate" header
//
// RFC 6749, section 5.2.:
// "If the client attempted to authenticate via the 'Authorization'
// request header field, the authorization server MUST
// respond with an HTTP 401 (Unauthorized) status code and
// include the "WWW-Authenticate" response header field
// matching the authentication scheme used by the client.
// @codeCoverageIgnoreStart
if ($error === 'invalid_client') {
$authScheme = null;
$request = new Request();
if ($request->server('PHP_AUTH_USER') !== null) {
$authScheme = 'Basic';
} else {
$authHeader = $request->header('Authorization');
if ($authHeader !== null) {
if (strpos($authHeader, 'Bearer') === 0) {
$authScheme = 'Bearer';
} elseif (strpos($authHeader, 'Basic') === 0) {
$authScheme = 'Basic';
}
}
}
if ($authScheme !== null) {
$headers[] = 'WWW-Authenticate: '.$authScheme.' realm=""';
}
}
// @codeCoverageIgnoreEnd
return $headers;
}
/**
* Get an exception message
*
@@ -142,7 +227,7 @@ class AuthServer
*/
public function __construct(ClientInterface $client, SessionInterface $session, ScopeInterface $scope)
{
self::$storages = array(
$this->storages = array(
'client' => $client,
'session' => $session,
'scope' => $scope
@@ -159,7 +244,7 @@ class AuthServer
if (is_null($identifier)) {
$identifier = $grantType->getIdentifier();
}
self::$grantTypes[$identifier] = $grantType;
$this->grantTypes[$identifier] = $grantType;
if ( ! is_null($grantType->getResponseType())) {
$this->responseTypes[] = $grantType->getResponseType();
@@ -171,9 +256,14 @@ class AuthServer
* @param string $identifier The grant type identifier
* @return boolean Returns "true" if enabled, "false" if not
*/
public static function hasGrantType($identifier)
public function hasGrantType($identifier)
{
return (array_key_exists($identifier, self::$grantTypes));
return (array_key_exists($identifier, $this->grantTypes));
}
public function getResponseTypes()
{
return $this->responseTypes;
}
/**
@@ -181,11 +271,48 @@ class AuthServer
* @param boolean $require
* @return void
*/
public function requireScopeParam($require = true)
public function requireScopeParam($require = false)
{
$this->requireScopeParam = $require;
}
/**
* Is the scope parameter required?
* @return bool
*/
public function scopeParamRequired()
{
return $this->requireScopeParam;
}
/**
* Default scope to be used if none is provided and requireScopeParam is false
* @var string|array
*/
public function setDefaultScope($default = null)
{
$this->defaultScope = $default;
}
/**
* Default scope to be used if none is provided and requireScopeParam is false
* @return string|null
*/
public function getDefaultScope()
{
return $this->defaultScope;
}
/**
* Require the "state" paremter in checkAuthoriseParams()
* @param boolean $require
* @return void
*/
public function stateParamRequired()
{
return $this->requireStateParam;
}
/**
* Require the "state" paremter in checkAuthoriseParams()
* @param boolean $require
@@ -211,7 +338,7 @@ class AuthServer
*
* @param string $scopeDelimeter
*/
public function setScopeDelimeter($scopeDelimeter)
public function setScopeDelimeter($scopeDelimeter = ' ')
{
$this->scopeDelimeter = $scopeDelimeter;
}
@@ -220,18 +347,18 @@ class AuthServer
* Get the TTL for an access token
* @return int The TTL
*/
public static function getExpiresIn()
public function getAccessTokenTTL()
{
return self::$expiresIn;
return $this->accessTokenTTL;
}
/**
* Set the TTL for an access token
* @param int $expiresIn The new TTL
* @param int $accessTokenTTL The new TTL
*/
public function setExpiresIn($expiresIn)
public function setAccessTokenTTL($accessTokenTTL = 3600)
{
self::$expiresIn = $expiresIn;
$this->accessTokenTTL = $accessTokenTTL;
}
/**
@@ -241,7 +368,7 @@ class AuthServer
*/
public function setRequest(Util\RequestInterface $request)
{
self::$request = $request;
$this->request = $request;
}
/**
@@ -249,16 +376,16 @@ class AuthServer
*
* @return Util\RequestInterface
*/
public static function getRequest()
public function getRequest()
{
if (self::$request === null) {
if ($this->request === null) {
// @codeCoverageIgnoreStart
self::$request = Request::buildFromGlobals();
$this->request = Request::buildFromGlobals();
}
// @codeCoverageIgnoreEnd
return self::$request;
return $this->request;
}
/**
@@ -266,106 +393,9 @@ class AuthServer
* @param string $obj The class required
* @return Storage\ClientInterface|Storage\ScopeInterface|Storage\SessionInterface
*/
public static function getStorage($obj)
public function getStorage($obj)
{
return self::$storages[$obj];
}
/**
* Check authorise parameters
*
* @param array $inputParams Optional array of parsed $_GET keys
* @throws \OAuth2\Exception\ClientException
* @return array Authorise request parameters
*/
public function checkAuthoriseParams($inputParams = array())
{
// Auth params
$authParams = self::getParam(array('client_id', 'redirect_uri', 'response_type', 'scope', 'state'), 'get', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'client_id'), 0);
}
if (is_null($authParams['redirect_uri'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'redirect_uri'), 0);
}
if ($this->requireStateParam === true && is_null($authParams['state'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'state'), 0);
}
// Validate client ID and redirect URI
$clientDetails = self::getStorage('client')->getClient($authParams['client_id'], null, $authParams['redirect_uri']);
if ($clientDetails === false) {
throw new Exception\ClientException(self::$exceptionMessages['invalid_client'], 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['response_type'])) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'response_type'), 0);
}
// Ensure response type is one that is recognised
if ( ! in_array($authParams['response_type'], $this->responseTypes)) {
throw new Exception\ClientException(self::$exceptionMessages['unsupported_response_type'], 3);
}
// Validate scopes
$scopes = explode($this->scopeDelimeter, $authParams['scope']);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->requireScopeParam === true && count($scopes) === 0) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'scope'), 0);
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = self::getStorage('scope')->getScope($scope);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_scope'], $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
}
return $authParams;
}
/**
* Parse a new authorise request
*
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @param array $authParams The authorise request $_GET parameters
* @return string An authorisation code
*/
public function newAuthoriseRequest($type, $typeId, $authParams = array())
{
// Generate an auth code
$authCode = SecureKey::make();
// Remove any old sessions the user might have
self::getStorage('session')->deleteSession($authParams['client_id'], $type, $typeId);
// Create a new session
$sessionId = self::getStorage('session')->createSession($authParams['client_id'], $authParams['redirect_uri'], $type, $typeId, $authCode);
// Associate scopes with the new session
foreach ($authParams['scopes'] as $scope)
{
self::getStorage('session')->associateScope($sessionId, $scope['id']);
}
return $authCode;
return $this->storages[$obj];
}
/**
@@ -376,14 +406,14 @@ class AuthServer
*/
public function issueAccessToken($inputParams = array())
{
$grantType = self::getParam('grant_type', 'post', $inputParams);
$grantType = $this->getParam('grant_type', 'post', $inputParams);
if (is_null($grantType)) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['invalid_request'], 'grant_type'), 0);
}
// Ensure grant type is one that is recognised and is enabled
if ( ! in_array($grantType, array_keys(self::$grantTypes))) {
if ( ! in_array($grantType, array_keys($this->grantTypes))) {
throw new Exception\ClientException(sprintf(self::$exceptionMessages['unsupported_grant_type'], $grantType), 7);
}
@@ -394,28 +424,40 @@ class AuthServer
/**
* Return a grant type class
* @param string $grantType The grant type identifer
* @return class
* @return Grant\AuthCode|Grant\ClientCredentials|Grant\Implict|Grant\Password|Grant\RefreshToken
*/
protected function getGrantType($grantType)
public function getGrantType($grantType)
{
return self::$grantTypes[$grantType];
}
if (isset($this->grantTypes[$grantType])) {
return $this->grantTypes[$grantType];
}
throw new Exception\InvalidGrantTypeException(sprintf(self::$exceptionMessages['unsupported_grant_type'], $grantType), 9);
}
/**
* Get a parameter from passed input parameters or the Request class
* @param string|array $param Requried parameter
* @param string|array $param Required parameter
* @param string $method Get/put/post/delete
* @param array $inputParams Passed input parameters
* @return mixed 'Null' if parameter is missing
*/
public static function getParam($param = '', $method = 'get', $inputParams = array())
public function getParam($param = '', $method = 'get', $inputParams = array(), $default = null)
{
if (is_string($param)) {
return (isset($inputParams[$param])) ? $inputParams[$param] : self::getRequest()->{$method}($param);
if (isset($inputParams[$param])) {
return $inputParams[$param];
} elseif ($param === 'client_id' && ! is_null($clientId = $this->getRequest()->server('PHP_AUTH_USER'))) {
return $clientId;
} elseif ($param === 'client_secret' && ! is_null($clientSecret = $this->getRequest()->server('PHP_AUTH_PW'))) {
return $clientSecret;
} else {
return $this->getRequest()->{$method}($param, $default);
}
} else {
$response = array();
foreach ($param as $p) {
$response[$p] = self::getParam($p, $method, $inputParams);
$response[$p] = $this->getParam($p, $method, $inputParams);
}
return $response;
}

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Client Exception
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Exception;
namespace League\OAuth2\Server\Exception;
/**
* ClientException Exception

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Invalid Access Token Exception
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Exception;
namespace League\OAuth2\Server\Exception;
/**
* InvalidAccessToken Exception

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Invalid Grant Type Exception
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Exception;
namespace League\OAuth2\Server\Exception;
/**
* InvalidGrantTypeException Exception

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Base Exception
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Exception;
namespace League\OAuth2\Server\Exception;
/**
* Exception class

View File

@@ -0,0 +1,295 @@
<?php
/**
* OAuth 2.0 Auth code grant
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
/**
* Auth code grant class
*/
class AuthCode implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'authorization_code';
/**
* Response type
* @var string
*/
protected $responseType = 'code';
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Access token expires in override
* @var int
*/
protected $accessTokenTTL = null;
/**
* The TTL of the auth token
* @var integer
*/
protected $authTokenTTL = 600;
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Override the default access token expire time
* @param int $accessTokenTTL
* @return void
*/
public function setAccessTokenTTL($accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
}
/**
* Override the default access token expire time
* @param int $authTokenTTL
* @return void
*/
public function setAuthTokenTTL($authTokenTTL)
{
$this->authTokenTTL = $authTokenTTL;
}
/**
* Check authorise parameters
*
* @param array $inputParams Optional array of parsed $_GET keys
* @throws \OAuth2\Exception\ClientException
* @return array Authorise request parameters
*/
public function checkAuthoriseParams($inputParams = array())
{
// Auth params
$authParams = $this->authServer->getParam(array('client_id', 'redirect_uri', 'response_type', 'scope', 'state'), 'get', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['redirect_uri'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'redirect_uri'), 0);
}
if ($this->authServer->stateParamRequired() === true && is_null($authParams['state'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'state'), 0);
}
// Validate client ID and redirect URI
$clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], null, $authParams['redirect_uri'], $this->identifier);
if ($clientDetails === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['response_type'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'response_type'), 0);
}
// Ensure response type is one that is recognised
if ( ! in_array($authParams['response_type'], $this->authServer->getResponseTypes())) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('unsupported_response_type'), 3);
}
// Validate scopes
$scopes = explode($this->authServer->getScopeDelimeter(), $authParams['scope']);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->authServer->scopeParamRequired() === true && $this->authServer->getDefaultScope() === null && count($scopes) === 0) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
} elseif (count($scopes) === 0 && $this->authServer->getDefaultScope() !== null) {
if (is_array($this->authServer->getDefaultScope())) {
$scopes = $this->authServer->getDefaultScope();
} else {
$scopes = array($this->authServer->getDefaultScope());
}
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = $this->authServer->getStorage('scope')->getScope($scope, $authParams['client_id'], $this->identifier);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
}
return $authParams;
}
/**
* Parse a new authorise request
*
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @param array $authParams The authorise request $_GET parameters
* @return string An authorisation code
*/
public function newAuthoriseRequest($type, $typeId, $authParams = array())
{
// Generate an auth code
$authCode = SecureKey::make();
// Remove any old sessions the user might have
$this->authServer->getStorage('session')->deleteSession($authParams['client_id'], $type, $typeId);
// Create a new session
$sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], $type, $typeId);
// Associate a redirect URI
$this->authServer->getStorage('session')->associateRedirectUri($sessionId, $authParams['redirect_uri']);
// Associate the auth code
$authCodeId = $this->authServer->getStorage('session')->associateAuthCode($sessionId, $authCode, time() + $this->authTokenTTL);
// Associate the scopes to the auth code
foreach ($authParams['scopes'] as $scope) {
$this->authServer->getStorage('session')->associateAuthCodeScope($authCodeId, $scope['id']);
}
return $authCode;
}
/**
* Complete the auth code grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
if (is_null($authParams['redirect_uri'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'redirect_uri'), 0);
}
// Validate client ID and redirect URI
$clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri'], $this->identifier);
if ($clientDetails === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
// Validate the authorization code
if (is_null($authParams['code'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'code'), 0);
}
// Verify the authorization code matches the client_id and the request_uri
$authCodeDetails = $this->authServer->getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']);
if ( ! $authCodeDetails) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_grant'), 'code'), 9);
}
// Get any associated scopes
$scopes = $this->authServer->getStorage('session')->getAuthCodeScopes($authCodeDetails['authcode_id']);
// A session ID was returned so update it with an access token and remove the authorisation code
$accessToken = SecureKey::make();
$accessTokenExpiresIn = ($this->accessTokenTTL !== null) ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL();
$accessTokenExpires = time() + $accessTokenExpiresIn;
// Remove the auth code
$this->authServer->getStorage('session')->removeAuthCode($authCodeDetails['session_id']);
// Create an access token
$accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($authCodeDetails['session_id'], $accessToken, $accessTokenExpires);
// Associate scopes with the access token
if (count($scopes) > 0) {
foreach ($scopes as $scope) {
$this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['scope_id']);
}
}
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
// Associate a refresh token if set
if ($this->authServer->hasGrantType('refresh_token')) {
$refreshToken = SecureKey::make();
$refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL();
$this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL, $authParams['client_id']);
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -0,0 +1,174 @@
<?php
/**
* OAuth 2.0 Client credentials grant
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
/**
* Client credentials grant class
*/
class ClientCredentials implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'client_credentials';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Access token expires in override
* @var int
*/
protected $accessTokenTTL = null;
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Override the default access token expire time
* @param int $accessTokenTTL
* @return void
*/
public function setAccessTokenTTL($accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
}
/**
* Complete the client credentials grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = $this->authServer->getParam(array('client_id', 'client_secret'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(Authorization::getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(Authorization::getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client ID and client secret
$clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier);
if ($clientDetails === false) {
throw new Exception\ClientException(Authorization::getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
// Validate any scopes that are in the request
$scope = $this->authServer->getParam('scope', 'post', $inputParams, '');
$scopes = explode($this->authServer->getScopeDelimeter(), $scope);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->authServer->scopeParamRequired() === true && $this->authServer->getDefaultScope() === null && count($scopes) === 0) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
} elseif (count($scopes) === 0 && $this->authServer->getDefaultScope() !== null) {
if (is_array($this->authServer->getDefaultScope())) {
$scopes = $this->authServer->getDefaultScope();
} else {
$scopes = array($this->authServer->getDefaultScope());
}
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = $this->authServer->getStorage('scope')->getScope($scope, $authParams['client_id'], $this->identifier);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
}
// Generate an access token
$accessToken = SecureKey::make();
$accessTokenExpiresIn = ($this->accessTokenTTL !== null) ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL();
$accessTokenExpires = time() + $accessTokenExpiresIn;
// Create a new session
$sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'client', $authParams['client_id']);
// Add the access token
$accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires);
// Associate scopes with the new session
foreach ($authParams['scopes'] as $scope)
{
$this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']);
}
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
return $response;
}
}

View File

@@ -2,33 +2,40 @@
/**
* OAuth 2.0 Grant type interface
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Grant;
namespace League\OAuth2\Server\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
interface GrantTypeInterface
{
/**
* Returns the grant identifier (used to validate grant_type in OAuth2\AuthServer\issueAccessToken())
* @return string
*/
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer);
/**
* Returns the grant identifier (used to validate grant_type in League\OAuth2\Server\Authorization::issueAccessToken())
* @return string
*/
public function getIdentifier();
/**
* Returns the response type (used to validate response_type in OAuth2\AuthServer\checkAuthoriseParams())
* Returns the response type (used to validate response_type in League\OAuth2\Server\Grant\AuthCode::checkAuthoriseParams())
* @return null|string
*/
public function getResponseType();

View File

@@ -0,0 +1,107 @@
<?php
/**
* OAuth 2.0 implicit grant
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
/**
* Client credentials grant class
*/
class Implict implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'implicit';
/**
* Response type
* @var string
*/
protected $responseType = 'token';
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Complete the client credentials grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($authParams = null)
{
// Remove any old sessions the user might have
$this->authServer->getStorage('session')->deleteSession($authParams['client_id'], 'user', $authParams['user_id']);
// Generate a new access token
$accessToken = SecureKey::make();
// Compute expiry time
$accessTokenExpires = time() + $this->authServer->getAccessTokenTTL();
// Create a new session
$sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'user', $authParams['user_id']);
// Create an access token
$accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires);
// Associate scopes with the access token
foreach ($authParams['scopes'] as $scope) {
$this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']);
}
$response = array(
'access_token' => $accessToken
);
return $response;
}
}

View File

@@ -0,0 +1,225 @@
<?php
/**
* OAuth 2.0 Password grant
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
/**
* Password grant class
*/
class Password implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'password';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* Callback to authenticate a user's name and password
* @var function
*/
protected $callback = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Access token expires in override
* @var int
*/
protected $accessTokenTTL = null;
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Override the default access token expire time
* @param int $accessTokenTTL
* @return void
*/
public function setAccessTokenTTL($accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
}
/**
* Set the callback to verify a user's username and password
* @param callable $callback The callback function
* @return void
*/
public function setVerifyCredentialsCallback($callback)
{
$this->callback = $callback;
}
/**
* Return the callback function
* @return callable
*/
protected function getVerifyCredentialsCallback()
{
if (is_null($this->callback) || ! is_callable($this->callback)) {
throw new Exception\InvalidGrantTypeException('Null or non-callable callback set');
}
return $this->callback;
}
/**
* Complete the password grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'username', 'password'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client credentials
$clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier);
if ($clientDetails === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['username'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'username'), 0);
}
if (is_null($authParams['password'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'password'), 0);
}
// Check if user's username and password are correct
$userId = call_user_func($this->getVerifyCredentialsCallback(), $authParams['username'], $authParams['password']);
if ($userId === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_credentials'), 0);
}
// Validate any scopes that are in the request
$scope = $this->authServer->getParam('scope', 'post', $inputParams, '');
$scopes = explode($this->authServer->getScopeDelimeter(), $scope);
for ($i = 0; $i < count($scopes); $i++) {
$scopes[$i] = trim($scopes[$i]);
if ($scopes[$i] === '') unset($scopes[$i]); // Remove any junk scopes
}
if ($this->authServer->scopeParamRequired() === true && $this->authServer->getDefaultScope() === null && count($scopes) === 0) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
} elseif (count($scopes) === 0 && $this->authServer->getDefaultScope() !== null) {
if (is_array($this->authServer->getDefaultScope())) {
$scopes = $this->authServer->getDefaultScope();
} else {
$scopes = array($this->authServer->getDefaultScope());
}
}
$authParams['scopes'] = array();
foreach ($scopes as $scope) {
$scopeDetails = $this->authServer->getStorage('scope')->getScope($scope, $authParams['client_id'], $this->identifier);
if ($scopeDetails === false) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_scope'), $scope), 4);
}
$authParams['scopes'][] = $scopeDetails;
}
// Generate an access token
$accessToken = SecureKey::make();
$accessTokenExpiresIn = ($this->accessTokenTTL !== null) ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL();
$accessTokenExpires = time() + $accessTokenExpiresIn;
// Create a new session
$sessionId = $this->authServer->getStorage('session')->createSession($authParams['client_id'], 'user', $userId);
// Associate an access token with the session
$accessTokenId = $this->authServer->getStorage('session')->associateAccessToken($sessionId, $accessToken, $accessTokenExpires);
// Associate scopes with the access token
foreach ($authParams['scopes'] as $scope) {
$this->authServer->getStorage('session')->associateScope($accessTokenId, $scope['id']);
}
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
// Associate a refresh token if set
if ($this->authServer->hasGrantType('refresh_token')) {
$refreshToken = SecureKey::make();
$refreshTokenTTL = time() + $this->authServer->getGrantType('refresh_token')->getRefreshTokenTTL();
$this->authServer->getStorage('session')->associateRefreshToken($accessTokenId, $refreshToken, $refreshTokenTTL, $authParams['client_id']);
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -0,0 +1,243 @@
<?php
/**
* OAuth 2.0 Refresh token grant
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
/**
* Referesh token grant
*/
class RefreshToken implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'refresh_token';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* AuthServer instance
* @var AuthServer
*/
protected $authServer = null;
/**
* Access token expires in override
* @var int
*/
protected $accessTokenTTL = null;
/**
* Refresh token TTL
* @var integer
*/
protected $refreshTokenTTL = 604800;
/**
* Rotate refresh tokens
* @var boolean
*/
protected $rotateRefreshTokens = false;
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer)
{
$this->authServer = $authServer;
}
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Override the default access token expire time
* @param int $accessTokenTTL
* @return void
*/
public function setAccessTokenTTL($accessTokenTTL)
{
$this->accessTokenTTL = $accessTokenTTL;
}
/**
* Set the TTL of the refresh token
* @param int $refreshTokenTTL
* @return void
*/
public function setRefreshTokenTTL($refreshTokenTTL)
{
$this->refreshTokenTTL = $refreshTokenTTL;
}
/**
* Get the TTL of the refresh token
* @return int
*/
public function getRefreshTokenTTL()
{
return $this->refreshTokenTTL;
}
/**
* When a new access is token, expire the refresh token used and issue a new one.
* @param boolean $rotateRefreshTokens Set to true to enable (default = false)
* @return void
*/
public function rotateRefreshTokens($rotateRefreshTokens = false)
{
$this->rotateRefreshTokens = $rotateRefreshTokens;
}
/**
* Complete the refresh token grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = $this->authServer->getParam(array('client_id', 'client_secret', 'refresh_token', 'scope'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client ID and client secret
$clientDetails = $this->authServer->getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], null, $this->identifier);
if ($clientDetails === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['refresh_token'])) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'refresh_token'), 0);
}
// Validate refresh token
$accessTokenId = $this->authServer->getStorage('session')->validateRefreshToken($authParams['refresh_token'], $authParams['client_id']);
if ($accessTokenId === false) {
throw new Exception\ClientException($this->authServer->getExceptionMessage('invalid_refresh'), 0);
}
// Get the existing access token
$accessTokenDetails = $this->authServer->getStorage('session')->getAccessToken($accessTokenId);
// Get the scopes for the existing access token
$scopes = $this->authServer->getStorage('session')->getScopes($accessTokenDetails['access_token']);
// Generate new tokens and associate them to the session
$accessToken = SecureKey::make();
$accessTokenExpiresIn = ($this->accessTokenTTL !== null) ? $this->accessTokenTTL : $this->authServer->getAccessTokenTTL();
$accessTokenExpires = time() + $accessTokenExpiresIn;
// Associate the new access token with the session
$newAccessTokenId = $this->authServer->getStorage('session')->associateAccessToken($accessTokenDetails['session_id'], $accessToken, $accessTokenExpires);
if ($this->rotateRefreshTokens === true) {
// Generate a new refresh token
$refreshToken = SecureKey::make();
$refreshTokenExpires = time() + $this->getRefreshTokenTTL();
// Revoke the old refresh token
$this->authServer->getStorage('session')->removeRefreshToken($authParams['refresh_token']);
// Associate the new refresh token with the new access token
$this->authServer->getStorage('session')->associateRefreshToken($newAccessTokenId, $refreshToken, $refreshTokenExpires, $authParams['client_id']);
}
// There isn't a request for reduced scopes so assign the original ones (or we're not rotating scopes)
if ( ! isset($authParams['scope'])) {
foreach ($scopes as $scope) {
$this->authServer->getStorage('session')->associateScope($newAccessTokenId, $scope['id']);
}
} elseif ( isset($authParams['scope']) && $this->rotateRefreshTokens === true) {
// The request is asking for reduced scopes and rotate tokens is enabled
$reqestedScopes = explode($this->authServer->getScopeDelimeter(), $authParams['scope']);
for ($i = 0; $i < count($reqestedScopes); $i++) {
$reqestedScopes[$i] = trim($reqestedScopes[$i]);
if ($reqestedScopes[$i] === '') unset($reqestedScopes[$i]); // Remove any junk scopes
}
// Check that there aren't any new scopes being included
$existingScopes = array();
foreach ($scopes as $s) {
$existingScopes[] = $s['scope'];
}
foreach ($reqestedScopes as $reqScope) {
if ( ! in_array($reqScope, $existingScopes)) {
throw new Exception\ClientException(sprintf($this->authServer->getExceptionMessage('invalid_request'), 'scope'), 0);
}
// Associate with the new access token
$scopeDetails = $this->authServer->getStorage('scope')->getScope($reqScope, $authParams['client_id'], $this->identifier);
$this->authServer->getStorage('session')->associateScope($newAccessTokenId, $scopeDetails['id']);
}
}
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if ($this->rotateRefreshTokens === true) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -2,25 +2,24 @@
/**
* OAuth 2.0 Resource Server
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2;
namespace League\OAuth2\Server;
use OutOfBoundsException;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\SessionScopeInterface;
use OAuth2\Util\RequestInterface;
use OAuth2\Util\Request;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Util\RequestInterface;
use League\OAuth2\Server\Util\Request;
/**
* OAuth 2.0 Resource Server
*/
class ResourceServer
class Resource
{
/**
* The access token
@@ -70,6 +69,12 @@ class ResourceServer
*/
protected $tokenKey = 'access_token';
/**
* The client ID
* @var string
*/
protected $clientId = null;
/**
* Sets up the Resource
*
@@ -156,6 +161,15 @@ class ResourceServer
return $this->accessToken;
}
/**
* Gets the client ID that created the session
* @return string
*/
public function getClientId()
{
return $this->clientId;
}
/**
* Checks if the access token is valid or not.
*
@@ -164,24 +178,37 @@ class ResourceServer
*/
public function isValid()
{
$access_token = $this->determineAccessToken();
$accessToken = $this->determineAccessToken();
$result = $this->storages['session']->validateAccessToken($access_token);
$result = $this->storages['session']->validateAccessToken($accessToken);
if ( ! $result) {
throw new Exception\InvalidAccessTokenException('Access token is not valid');
}
$this->accessToken = $access_token;
$this->sessionId = $result['id'];
$this->accessToken = $accessToken;
$this->sessionId = $result['session_id'];
$this->clientId = $result['client_id'];
$this->ownerType = $result['owner_type'];
$this->ownerId = $result['owner_id'];
$this->sessionScopes = $this->storages['session']->getScopes($this->sessionId);
$sessionScopes = $this->storages['session']->getScopes($this->accessToken);
foreach ($sessionScopes as $scope) {
$this->sessionScopes[] = $scope['key'];
}
return true;
}
/**
* Get the session scopes
* @return array
*/
public function getScopes()
{
return $this->sessionScopes;
}
/**
* Checks if the presented access token has the given scope(s).
*
@@ -216,17 +243,29 @@ class ResourceServer
protected function determineAccessToken()
{
if ($header = $this->getRequest()->header('Authorization')) {
$access_token = base64_decode(trim(str_replace('Bearer', '', $header)));
// Check for special case, because cURL sometimes does an
// internal second request and doubles the authorization header,
// which always resulted in an error.
//
// 1st request: Authorization: Bearer XXX
// 2nd request: Authorization: Bearer XXX, Bearer XXX
if (strpos($header, ',') !== false) {
$headerPart = explode(',', $header);
$accessToken = preg_replace('/^(?:\s+)?Bearer(\s{1})/', '', $headerPart[0]);
} else {
$accessToken = preg_replace('/^(?:\s+)?Bearer(\s{1})/', '', $header);
}
$accessToken = ($accessToken === 'Bearer') ? '' : $accessToken;
} else {
$method = $this->getRequest()->server('REQUEST_METHOD');
$access_token = $this->getRequest()->{$method}($this->tokenKey);
$accessToken = $this->getRequest()->{$method}($this->tokenKey);
}
if (empty($access_token)) {
if (empty($accessToken)) {
throw new Exception\InvalidAccessTokenException('Access token is missing');
}
return $access_token;
return $accessToken;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* OAuth 2.0 Client storage interface
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Storage;
interface ClientInterface
{
/**
* Validate a client
*
* Example SQL query:
*
* <code>
* # Client ID + redirect URI
* SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name
* FROM oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id
* WHERE oauth_clients.id = :clientId AND oauth_client_endpoints.redirect_uri = :redirectUri
*
* # Client ID + client secret
* SELECT oauth_clients.id, oauth_clients.secret, oauth_clients.name FROM oauth_clients WHERE
* oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret
*
* # Client ID + client secret + redirect URI
* SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name FROM
* oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id
* WHERE oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret AND
* oauth_client_endpoints.redirect_uri = :redirectUri
* </code>
*
* Response:
*
* <code>
* Array
* (
* [client_id] => (string) The client ID
* [client secret] => (string) The client secret
* [redirect_uri] => (string) The redirect URI used in this request
* [name] => (string) The name of the client
* )
* </code>
*
* @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 in the request
* @return bool|array Returns false if the validation fails, array on success
*/
public function getClient($clientId, $clientSecret = null, $redirectUri = null, $grantType);
}

View File

@@ -0,0 +1,45 @@
<?php
namespace League\OAuth2\Server\Storage\PDO;
use League\OAuth2\Server\Storage\ClientInterface;
class Client implements ClientInterface
{
public function getClient($clientId, $clientSecret = null, $redirectUri = null, $grantType)
{
$db = \ezcDbInstance::get();
if ( ! is_null($redirectUri) && is_null($clientSecret)) {
$stmt = $db->prepare('SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name FROM oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id WHERE oauth_clients.id = :clientId AND oauth_client_endpoints.redirect_uri = :redirectUri');
$stmt->bindValue(':redirectUri', $redirectUri);
}
elseif ( ! is_null($clientSecret) && is_null($redirectUri)) {
$stmt = $db->prepare('SELECT oauth_clients.id, oauth_clients.secret, oauth_clients.name FROM oauth_clients WHERE oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret');
$stmt->bindValue(':clientSecret', $clientSecret);
}
elseif ( ! is_null($clientSecret) && ! is_null($redirectUri)) {
$stmt = $db->prepare('SELECT oauth_clients.id, oauth_clients.secret, oauth_client_endpoints.redirect_uri, oauth_clients.name FROM oauth_clients LEFT JOIN oauth_client_endpoints ON oauth_client_endpoints.client_id = oauth_clients.id WHERE oauth_clients.id = :clientId AND oauth_clients.secret = :clientSecret AND oauth_client_endpoints.redirect_uri = :redirectUri');
$stmt->bindValue(':redirectUri', $redirectUri);
$stmt->bindValue(':clientSecret', $clientSecret);
}
$stmt->bindValue(':clientId', $clientId);
$stmt->execute();
$row = $stmt->fetchObject();
if ($row === false) {
return false;
}
return array(
'client_id' => $row->id,
'client_secret' => $row->secret,
'redirect_uri' => (isset($row->redirect_uri)) ? $row->redirect_uri : null,
'name' => $row->name
);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace League\OAuth2\Server\Storage\PDO;
class Db
{
/**
* Db constructor
* @param array|string $dsn Connection DSN string or array of parameters
* @return void
*/
public function __construct($dsn = '')
{
$db = \ezcDbFactory::create($dsn);
\ezcDbInstance::set($db);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace League\OAuth2\Server\Storage\PDO;
use League\OAuth2\Server\Storage\ScopeInterface;
class Scope implements ScopeInterface
{
public function getScope($scope, $clientId = null, $grantType = null)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT * FROM oauth_scopes WHERE oauth_scopes.scope = :scope');
$stmt->bindValue(':scope', $scope);
$stmt->execute();
$row = $stmt->fetchObject();
if ($row === false) {
return false;
}
return array(
'id' => $row->id,
'scope' => $row->scope,
'name' => $row->name,
'description' => $row->description
);
}
}

View File

@@ -0,0 +1,206 @@
<?php
namespace League\OAuth2\Server\Storage\PDO;
use League\OAuth2\Server\Storage\SessionInterface;
class Session implements SessionInterface
{
public function createSession($clientId, $ownerType, $ownerId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO oauth_sessions (client_id, owner_type, owner_id) VALUE
(:clientId, :ownerType, :ownerId)');
$stmt->bindValue(':clientId', $clientId);
$stmt->bindValue(':ownerType', $ownerType);
$stmt->bindValue(':ownerId', $ownerId);
$stmt->execute();
return $db->lastInsertId();
}
public function deleteSession($clientId, $ownerType, $ownerId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('DELETE FROM oauth_sessions WHERE client_id = :clientId AND
owner_type = :type AND owner_id = :typeId');
$stmt->bindValue(':clientId', $clientId);
$stmt->bindValue(':type', $ownerType);
$stmt->bindValue(':typeId', $ownerId);
$stmt->execute();
}
public function associateRedirectUri($sessionId, $redirectUri)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO oauth_session_redirects (session_id, redirect_uri)
VALUE (:sessionId, :redirectUri)');
$stmt->bindValue(':sessionId', $sessionId);
$stmt->bindValue(':redirectUri', $redirectUri);
$stmt->execute();
}
public function associateAccessToken($sessionId, $accessToken, $expireTime)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO oauth_session_access_tokens (session_id, access_token, access_token_expires)
VALUE (:sessionId, :accessToken, :accessTokenExpire)');
$stmt->bindValue(':sessionId', $sessionId);
$stmt->bindValue(':accessToken', $accessToken);
$stmt->bindValue(':accessTokenExpire', $expireTime);
$stmt->execute();
return $db->lastInsertId();
}
public function associateRefreshToken($accessTokenId, $refreshToken, $expireTime, $clientId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO oauth_session_refresh_tokens (session_access_token_id, refresh_token, refresh_token_expires, client_id) VALUE
(:accessTokenId, :refreshToken, :expireTime, :clientId)');
$stmt->bindValue(':accessTokenId', $accessTokenId);
$stmt->bindValue(':refreshToken', $refreshToken);
$stmt->bindValue(':expireTime', $expireTime);
$stmt->bindValue(':clientId', $clientId);
$stmt->execute();
}
public function associateAuthCode($sessionId, $authCode, $expireTime)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO oauth_session_authcodes (session_id, auth_code, auth_code_expires)
VALUE (:sessionId, :authCode, :authCodeExpires)');
$stmt->bindValue(':sessionId', $sessionId);
$stmt->bindValue(':authCode', $authCode);
$stmt->bindValue(':authCodeExpires', $expireTime);
$stmt->execute();
return $db->lastInsertId();
}
public function removeAuthCode($sessionId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('DELETE FROM oauth_session_authcodes WHERE session_id = :sessionId');
$stmt->bindValue(':sessionId', $sessionId);
$stmt->execute();
}
public function validateAuthCode($clientId, $redirectUri, $authCode)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT oauth_sessions.id AS session_id, oauth_session_authcodes.id AS authcode_id
FROM oauth_sessions JOIN oauth_session_authcodes ON oauth_session_authcodes.`session_id`
= oauth_sessions.id JOIN oauth_session_redirects ON oauth_session_redirects.`session_id`
= oauth_sessions.id WHERE oauth_sessions.client_id = :clientId AND oauth_session_authcodes.`auth_code`
= :authCode AND `oauth_session_authcodes`.`auth_code_expires` >= :time AND
`oauth_session_redirects`.`redirect_uri` = :redirectUri');
$stmt->bindValue(':clientId', $clientId);
$stmt->bindValue(':redirectUri', $redirectUri);
$stmt->bindValue(':authCode', $authCode);
$stmt->bindValue(':time', time());
$stmt->execute();
$result = $stmt->fetchObject();
return ($result === false) ? false : (array) $result;
}
public function validateAccessToken($accessToken)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT session_id, oauth_sessions.`client_id`, oauth_sessions.`owner_id`, oauth_sessions.`owner_type` FROM `oauth_session_access_tokens` JOIN oauth_sessions ON oauth_sessions.`id` = session_id WHERE access_token = :accessToken AND access_token_expires >= ' . time());
$stmt->bindValue(':accessToken', $accessToken);
$stmt->execute();
$result = $stmt->fetchObject();
return ($result === false) ? false : (array) $result;
}
public function removeRefreshToken($refreshToken)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('DELETE FROM `oauth_session_refresh_tokens` WHERE refresh_token = :refreshToken');
$stmt->bindValue(':refreshToken', $refreshToken);
$stmt->execute();
}
public function validateRefreshToken($refreshToken, $clientId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT session_access_token_id FROM `oauth_session_refresh_tokens` WHERE
refresh_token = :refreshToken AND client_id = :clientId AND refresh_token_expires >= ' . time());
$stmt->bindValue(':refreshToken', $refreshToken);
$stmt->bindValue(':clientId', $clientId);
$stmt->execute();
$result = $stmt->fetchObject();
return ($result === false) ? false : $result->session_access_token_id;
}
public function getAccessToken($accessTokenId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT * FROM `oauth_session_access_tokens` WHERE `id` = :accessTokenId');
$stmt->bindValue(':accessTokenId', $accessTokenId);
$stmt->execute();
$result = $stmt->fetchObject();
return ($result === false) ? false : (array) $result;
}
public function associateAuthCodeScope($authCodeId, $scopeId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO `oauth_session_authcode_scopes` (`oauth_session_authcode_id`, `scope_id`) VALUES (:authCodeId, :scopeId)');
$stmt->bindValue(':authCodeId', $authCodeId);
$stmt->bindValue(':scopeId', $scopeId);
$stmt->execute();
}
public function getAuthCodeScopes($oauthSessionAuthCodeId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT scope_id FROM `oauth_session_authcode_scopes` WHERE oauth_session_authcode_id = :authCodeId');
$stmt->bindValue(':authCodeId', $oauthSessionAuthCodeId);
$stmt->execute();
return $stmt->fetchAll();
}
public function associateScope($accessTokenId, $scopeId)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('INSERT INTO `oauth_session_token_scopes` (`session_access_token_id`, `scope_id`)
VALUE (:accessTokenId, :scopeId)');
$stmt->bindValue(':accessTokenId', $accessTokenId);
$stmt->bindValue(':scopeId', $scopeId);
$stmt->execute();
}
public function getScopes($accessToken)
{
$db = \ezcDbInstance::get();
$stmt = $db->prepare('SELECT oauth_scopes.* FROM oauth_session_token_scopes JOIN oauth_session_access_tokens ON oauth_session_access_tokens.`id` = `oauth_session_token_scopes`.`session_access_token_id` JOIN oauth_scopes ON oauth_scopes.id = `oauth_session_token_scopes`.`scope_id` WHERE access_token = :accessToken');
$stmt->bindValue(':accessToken', $accessToken);
$stmt->execute();
return $stmt->fetchAll();
}
}

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Scope storage interface
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Storage;
namespace League\OAuth2\Server\Storage;
interface ScopeInterface
{
@@ -19,7 +19,7 @@ interface ScopeInterface
* Example SQL query:
*
* <code>
* SELECT * FROM oauth_scopes WHERE scope = $scope
* SELECT * FROM oauth_scopes WHERE scope = :scope
* </code>
*
* Response:
@@ -34,8 +34,10 @@ interface ScopeInterface
* )
* </code>
*
* @param string $scope The scope
* @param string $scope The scope
* @param string $clientId The client ID
* @param string $grantType The grant type used in the request
* @return bool|array If the scope doesn't exist return false
*/
public function getScope($scope);
public function getScope($scope, $clientId = null, $grantType = null);
}

View File

@@ -0,0 +1,331 @@
<?php
/**
* OAuth 2.0 Session storage interface
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Storage;
interface SessionInterface
{
/**
* Create a new session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_sessions (client_id, owner_type, owner_id)
* VALUE (:clientId, :ownerType, :ownerId)
* </code>
*
* @param string $clientId The client ID
* @param string $ownerType The type of the session owner (e.g. "user")
* @param string $ownerId The ID of the session owner (e.g. "123")
* @return int The session ID
*/
public function createSession($clientId, $ownerType, $ownerId);
/**
* Delete a session
*
* Example SQL query:
*
* <code>
* DELETE FROM oauth_sessions WHERE client_id = :clientId AND owner_type = :type AND owner_id = :typeId
* </code>
*
* @param string $clientId The client ID
* @param string $ownerType The type of the session owner (e.g. "user")
* @param string $ownerId The ID of the session owner (e.g. "123")
* @return void
*/
public function deleteSession($clientId, $ownerType, $ownerId);
/**
* Associate a redirect URI with a session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_session_redirects (session_id, redirect_uri) VALUE (:sessionId, :redirectUri)
* </code>
*
* @param int $sessionId The session ID
* @param string $redirectUri The redirect URI
* @return void
*/
public function associateRedirectUri($sessionId, $redirectUri);
/**
* Associate an access token with a session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_session_access_tokens (session_id, access_token, access_token_expires)
* VALUE (:sessionId, :accessToken, :accessTokenExpire)
* </code>
*
* @param int $sessionId The session ID
* @param string $accessToken The access token
* @param int $expireTime Unix timestamp of the access token expiry time
* @return void
*/
public function associateAccessToken($sessionId, $accessToken, $expireTime);
/**
* Associate a refresh token with a session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_session_refresh_tokens (session_access_token_id, refresh_token, refresh_token_expires,
* client_id) VALUE (:accessTokenId, :refreshToken, :expireTime, :clientId)
* </code>
*
* @param int $accessTokenId The access token ID
* @param string $refreshToken The refresh token
* @param int $expireTime Unix timestamp of the refresh token expiry time
* @param string $clientId The client ID
* @return void
*/
public function associateRefreshToken($accessTokenId, $refreshToken, $expireTime, $clientId);
/**
* Assocate an authorization code with a session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_session_authcodes (session_id, auth_code, auth_code_expires)
* VALUE (:sessionId, :authCode, :authCodeExpires)
* </code>
*
* @param int $sessionId The session ID
* @param string $authCode The authorization code
* @param int $expireTime Unix timestamp of the access token expiry time
* @return int The auth code ID
*/
public function associateAuthCode($sessionId, $authCode, $expireTime);
/**
* Remove an associated authorization token from a session
*
* Example SQL query:
*
* <code>
* DELETE FROM oauth_session_authcodes WHERE session_id = :sessionId
* </code>
*
* @param int $sessionId The session ID
* @return void
*/
public function removeAuthCode($sessionId);
/**
* Validate an authorization code
*
* Example SQL query:
*
* <code>
* SELECT oauth_sessions.id AS session_id, oauth_session_authcodes.id AS authcode_id FROM oauth_sessions
* JOIN oauth_session_authcodes ON oauth_session_authcodes.`session_id` = oauth_sessions.id
* JOIN oauth_session_redirects ON oauth_session_redirects.`session_id` = oauth_sessions.id WHERE
* oauth_sessions.client_id = :clientId AND oauth_session_authcodes.`auth_code` = :authCode
* AND `oauth_session_authcodes`.`auth_code_expires` >= :time AND
* `oauth_session_redirects`.`redirect_uri` = :redirectUri
* </code>
*
* Expected response:
*
* <code>
* array(
* 'session_id' => (int)
* 'authcode_id' => (int)
* )
* </code>
*
* @param string $clientId The client ID
* @param string $redirectUri The redirect URI
* @param string $authCode The authorization code
* @return array|bool False if invalid or array as above
*/
public function validateAuthCode($clientId, $redirectUri, $authCode);
/**
* Validate an access token
*
* Example SQL query:
*
* <code>
* SELECT session_id, oauth_sessions.`client_id`, oauth_sessions.`owner_id`, oauth_sessions.`owner_type`
* FROM `oauth_session_access_tokens` JOIN oauth_sessions ON oauth_sessions.`id` = session_id WHERE
* access_token = :accessToken AND access_token_expires >= UNIX_TIMESTAMP(NOW())
* </code>
*
* Expected response:
*
* <code>
* array(
* 'session_id' => (int),
* 'client_id' => (string),
* 'owner_id' => (string),
* 'owner_type' => (string)
* )
* </code>
*
* @param string $accessToken The access token
* @return array|bool False if invalid or an array as above
*/
public function validateAccessToken($accessToken);
/**
* Removes a refresh token
*
* Example SQL query:
*
* <code>
* DELETE FROM `oauth_session_refresh_tokens` WHERE refresh_token = :refreshToken
* </code>
*
* @param string $refreshToken The refresh token to be removed
* @return void
*/
public function removeRefreshToken($refreshToken);
/**
* Validate a refresh token
*
* Example SQL query:
*
* <code>
* SELECT session_access_token_id FROM `oauth_session_refresh_tokens` WHERE refresh_token = :refreshToken
* AND refresh_token_expires >= UNIX_TIMESTAMP(NOW()) AND client_id = :clientId
* </code>
*
* @param string $refreshToken The access token
* @param string $clientId The client ID
* @return int|bool The ID of the access token the refresh token is linked to (or false if invalid)
*/
public function validateRefreshToken($refreshToken, $clientId);
/**
* Get an access token by ID
*
* Example SQL query:
*
* <code>
* SELECT * FROM `oauth_session_access_tokens` WHERE `id` = :accessTokenId
* </code>
*
* Expected response:
*
* <code>
* array(
* 'id' => (int),
* 'session_id' => (int),
* 'access_token' => (string),
* 'access_token_expires' => (int)
* )
* </code>
*
* @param int $accessTokenId The access token ID
* @return array
*/
public function getAccessToken($accessTokenId);
/**
* Associate scopes with an auth code (bound to the session)
*
* Example SQL query:
*
* <code>
* INSERT INTO `oauth_session_authcode_scopes` (`oauth_session_authcode_id`, `scope_id`) VALUES
* (:authCodeId, :scopeId)
* </code>
*
* @param int $authCodeId The auth code ID
* @param int $scopeId The scope ID
* @return void
*/
public function associateAuthCodeScope($authCodeId, $scopeId);
/**
* Get the scopes associated with an auth code
*
* Example SQL query:
*
* <code>
* SELECT scope_id FROM `oauth_session_authcode_scopes` WHERE oauth_session_authcode_id = :authCodeId
* </code>
*
* Expected response:
*
* <code>
* array(
* array(
* 'scope_id' => (int)
* ),
* array(
* 'scope_id' => (int)
* ),
* ...
* )
* </code>
*
* @param int $oauthSessionAuthCodeId The session ID
* @return array
*/
public function getAuthCodeScopes($oauthSessionAuthCodeId);
/**
* Associate a scope with an access token
*
* Example SQL query:
*
* <code>
* INSERT INTO `oauth_session_token_scopes` (`session_access_token_id`, `scope_id`) VALUE (:accessTokenId, :scopeId)
* </code>
*
* @param int $accessTokenId The ID of the access token
* @param int $scopeId The ID of the scope
* @return void
*/
public function associateScope($accessTokenId, $scopeId);
/**
* Get all associated access tokens for an access token
*
* Example SQL query:
*
* <code>
* SELECT oauth_scopes.* FROM oauth_session_token_scopes JOIN oauth_session_access_tokens
* ON oauth_session_access_tokens.`id` = `oauth_session_token_scopes`.`session_access_token_id`
* JOIN oauth_scopes ON oauth_scopes.id = `oauth_session_token_scopes`.`scope_id`
* WHERE access_token = :accessToken
* </code>
*
* Expected response:
*
* <code>
* array (
* array(
* 'key' => (string),
* 'name' => (string),
* 'description' => (string)
* ),
* ...
* ...
* )
* </code>
*
* @param string $accessToken The access token
* @return array
*/
public function getScopes($accessToken);
}

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Redirect URI generator
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Util;
namespace League\OAuth2\Server\Util;
/**
* RedirectUri class

View File

@@ -1,6 +1,15 @@
<?php
/**
* OAuth 2.0 Request class
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Util;
namespace League\OAuth2\Server\Util;
use OutOfBoundsException;
use InvalidMethodCallException;

View File

@@ -1,6 +1,15 @@
<?php
/**
* OAuth 2.0 Request class interface
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Util;
namespace League\OAuth2\Server\Util;
interface RequestInterface
{

View File

@@ -2,14 +2,14 @@
/**
* OAuth 2.0 Secure key generator
*
* @package lncd/oauth2
* @package php-loep/oauth2-server
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
* @link http://github.com/php-loep/oauth2-server
*/
namespace OAuth2\Util;
namespace League\OAuth2\Server\Util;
/**
* SecureKey class

View File

@@ -1,132 +0,0 @@
<?php
/**
* OAuth 2.0 Auth code grant
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
/**
* Auth code grant class
*/
class AuthCode implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'authorization_code';
/**
* Response type
* @var string
*/
protected $responseType = 'code';
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Complete the auth code grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'redirect_uri', 'code'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
if (is_null($authParams['redirect_uri'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'redirect_uri'), 0);
}
// Validate client ID and redirect URI
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret'], $authParams['redirect_uri']);
if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
// Validate the authorization code
if (is_null($authParams['code'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'code'), 0);
}
// Verify the authorization code matches the client_id and the request_uri
$session = AuthServer::getStorage('session')->validateAuthCode($authParams['client_id'], $authParams['redirect_uri'], $authParams['code']);
if ( ! $session) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_grant'), 'code'), 9);
}
// A session ID was returned so update it with an access token,
// remove the authorisation code, change the stage to 'granted'
$accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn();
AuthServer::getStorage('session')->updateSession(
$session['id'],
null,
$accessToken,
$refreshToken,
$accessTokenExpires,
'granted'
);
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if (AuthServer::hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -1,121 +0,0 @@
<?php
/**
* OAuth 2.0 Auth code grant
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
/**
* Client credentials grant class
*/
class ClientCredentials implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'client_credentials';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Complete the client credentials grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client ID and client secret
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
// Generate an access token
$accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn();
// Delete any existing sessions just to be sure
AuthServer::getStorage('session')->deleteSession($authParams['client_id'], 'client', $authParams['client_id']);
// Create a new session
AuthServer::getStorage('session')->createSession(
$authParams['client_id'],
null,
'client',
$authParams['client_id'],
null,
$accessToken,
$refreshToken,
$accessTokenExpires,
'granted'
);
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if (AuthServer::hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -1,164 +0,0 @@
<?php
/**
* OAuth 2.0 Password grant
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
/**
* Password grant class
*/
class Password implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'password';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* Callback to authenticate a user's name and password
* @var function
*/
protected $callback = null;
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Set the callback to verify a user's username and password
* @param function $callback The callback function
*/
public function setVerifyCredentialsCallback($callback)
{
$this->callback = $callback;
}
/**
* Return the callback function
* @return function
*/
protected function getVerifyCredentialsCallback()
{
if (is_null($this->callback) || ! is_callable($this->callback)) {
throw new Exception\InvalidGrantTypeException('Null or non-callable callback set');
}
return $this->callback;
}
/**
* Complete the password grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'username', 'password'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client ID and redirect URI
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['username'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'username'), 0);
}
if (is_null($authParams['password'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'password'), 0);
}
// Check if user's username and password are correct
$userId = call_user_func($this->getVerifyCredentialsCallback(), $authParams['username'], $authParams['password']);
if ($userId === false || $userId === null) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_credentials'), 0);
}
// Generate an access token
$accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn();
// Delete any existing sessions just to be sure
AuthServer::getStorage('session')->deleteSession($authParams['client_id'], 'user', $userId);
// Create a new session
AuthServer::getStorage('session')->createSession(
$authParams['client_id'],
null,
'user',
$userId,
null,
$accessToken,
$refreshToken,
$accessTokenExpires,
'granted'
);
$response = array(
'access_token' => $accessToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
if (AuthServer::hasGrantType('refresh_token')) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -1,116 +0,0 @@
<?php
/**
* OAuth 2.0 Refresh token grant
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Grant;
use OAuth2\Request;
use OAuth2\AuthServer;
use OAuth2\Exception;
use OAuth2\Util\SecureKey;
use OAuth2\Storage\SessionInterface;
use OAuth2\Storage\ClientInterface;
use OAuth2\Storage\ScopeInterface;
/**
* Referesh token grant
*/
class RefreshToken implements GrantTypeInterface {
/**
* Grant identifier
* @var string
*/
protected $identifier = 'refresh_token';
/**
* Response type
* @var string
*/
protected $responseType = null;
/**
* Return the identifier
* @return string
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* Return the response type
* @return string
*/
public function getResponseType()
{
return $this->responseType;
}
/**
* Complete the refresh token grant
* @param null|array $inputParams
* @return array
*/
public function completeFlow($inputParams = null)
{
// Get the required params
$authParams = AuthServer::getParam(array('client_id', 'client_secret', 'refresh_token'), 'post', $inputParams);
if (is_null($authParams['client_id'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_id'), 0);
}
if (is_null($authParams['client_secret'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'client_secret'), 0);
}
// Validate client ID and client secret
$clientDetails = AuthServer::getStorage('client')->getClient($authParams['client_id'], $authParams['client_secret']);
if ($clientDetails === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_client'), 8);
}
$authParams['client_details'] = $clientDetails;
if (is_null($authParams['refresh_token'])) {
throw new Exception\ClientException(sprintf(AuthServer::getExceptionMessage('invalid_request'), 'refresh_token'), 0);
}
// Validate refresh token
$sessionId = AuthServer::getStorage('client')->validateRefreshToken(
$authParams['refresh_token'],
$authParams['client_id']
);
if ($sessionId === false) {
throw new Exception\ClientException(AuthServer::getExceptionMessage('invalid_refresh'), 0);
}
// Generate new tokens
$accessToken = SecureKey::make();
$refreshToken = (AuthServer::hasGrantType('refresh_token')) ? SecureKey::make() : null;
$accessTokenExpires = time() + AuthServer::getExpiresIn();
$accessTokenExpiresIn = AuthServer::getExpiresIn();
AuthServer::getStorage('session')->updateRefreshToken($sessionId, $accessToken, $refreshToken, $accessTokenExpires);
return array(
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
'token_type' => 'bearer',
'expires' => $accessTokenExpires,
'expires_in' => $accessTokenExpiresIn
);
}
}

View File

@@ -1,54 +0,0 @@
<?php
/**
* OAuth 2.0 Client storage interface
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Storage;
interface ClientInterface
{
/**
* Validate a client
*
* Example SQL query:
*
* <code>
* # Client ID + redirect URI
* SELECT oauth_clients.id FROM oauth_clients LEFT JOIN client_endpoints ON client_endpoints.client_id
* = oauth_clients.id WHERE oauth_clients.id = $clientId AND client_endpoints.redirect_uri = $redirectUri
*
* # Client ID + client secret
* SELECT oauth_clients.id FROM oauth_clients WHERE oauth_clients.id = $clientId AND
* oauth_clients.secret = $clientSecret
*
* # Client ID + client secret + redirect URI
* SELECT oauth_clients.id FROM oauth_clients LEFT JOIN client_endpoints ON client_endpoints.client_id
* = oauth_clients.id WHERE oauth_clients.id = $clientId AND oauth_clients.secret = $clientSecret
* AND client_endpoints.redirect_uri = $redirectUri
* </code>
*
* Response:
*
* <code>
* Array
* (
* [client_id] => (string) The client ID
* [client secret] => (string) The client secret
* [redirect_uri] => (string) The redirect URI used in this request
* [name] => (string) The name of the client
* )
* </code>
*
* @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")
* @return bool|array Returns false if the validation fails, array on success
*/
public function getClient($clientId = null, $clientSecret = null, $redirectUri = null);
}

View File

@@ -1,236 +0,0 @@
<?php
/**
* OAuth 2.0 Session storage interface
*
* @package lncd/oauth2
* @author Alex Bilbie <hello@alexbilbie.com>
* @copyright Copyright (c) 2013 University of Lincoln
* @license http://mit-license.org/
* @link http://github.com/lncd/oauth2
*/
namespace OAuth2\Storage;
interface SessionInterface
{
/**
* Create a new OAuth session
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_sessions (client_id, redirect_uri, owner_type,
* owner_id, auth_code, access_token, refresh_token, stage, first_requested,
* last_updated) VALUES ($clientId, $redirectUri, $type, $typeId, $authCode,
* $accessToken, $stage, UNIX_TIMESTAMP(NOW()), UNIX_TIMESTAMP(NOW()))
* </code>
*
* @param string $clientId The client ID
* @param string $redirectUri The redirect URI
* @param string $type The session owner's type (default = "user")
* @param string $typeId The session owner's ID (default = "null")
* @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null")
* @param string $refreshToken The refresh token (default = "null")
* @param int $accessTokenExpire The expiry time of an access token as a unix timestamp
* @param string $stage The stage of the session (default ="request")
* @return int The session ID
*/
public function createSession(
$clientId,
$redirectUri,
$type = 'user',
$typeId = null,
$authCode = null,
$accessToken = null,
$refreshToken = null,
$accessTokenExpire = null,
$stage = 'requested'
);
/**
* Update an OAuth session
*
* Example SQL query:
*
* <code>
* UPDATE oauth_sessions SET auth_code = $authCode, access_token =
* $accessToken, stage = $stage, last_updated = UNIX_TIMESTAMP(NOW()) WHERE
* id = $sessionId
* </code>
*
* @param string $sessionId The session ID
* @param string $authCode The authorisation code (default = "null")
* @param string $accessToken The access token (default = "null")
* @param string $refreshToken The refresh token (default = "null")
* @param int $accessTokenExpire The expiry time of an access token as a unix timestamp
* @param string $stage The stage of the session (default ="request")
* @return void
*/
public function updateSession(
$sessionId,
$authCode = null,
$accessToken = null,
$refreshToken = null,
$accessTokenExpire = null,
$stage = 'requested'
);
/**
* Delete an OAuth session
*
* <code>
* DELETE FROM oauth_sessions WHERE client_id = $clientId AND owner_type =
* $type AND owner_id = $typeId
* </code>
*
* @param string $clientId The client ID
* @param string $type The session owner's type
* @param string $typeId The session owner's ID
* @return void
*/
public function deleteSession(
$clientId,
$type,
$typeId
);
/**
* Validate that an authorisation code is valid
*
* Example SQL query:
*
* <code>
* SELECT id FROM oauth_sessions WHERE client_id = $clientID AND
* redirect_uri = $redirectUri AND auth_code = $authCode
* </code>
*
* @param string $clientId The client ID
* @param string $redirectUri The redirect URI
* @param string $authCode The authorisation code
* @return int|bool Returns the session ID if the auth code
* is valid otherwise returns false
*/
public function validateAuthCode(
$clientId,
$redirectUri,
$authCode
);
/**
* Validate an access token
*
* Example SQL query:
*
* <code>
* SELECT id, owner_id, owner_type FROM oauth_sessions WHERE access_token = $accessToken
* </code>
*
* Response:
*
* <code>
* Array
* (
* [id] => (int) The session ID
* [owner_type] => (string) The owner type
* [owner_id] => (string) The owner ID
* )
* </code>
*
* @param [type] $accessToken [description]
* @return [type] [description]
*/
public function validateAccessToken($accessToken);
/**
* Return the access token for a given session
*
* Example SQL query:
*
* <code>
* SELECT access_token FROM oauth_sessions WHERE id = $sessionId
* </code>
*
* @param int $sessionId The OAuth session ID
* @return string|null Returns the access token as a string if
* found otherwise returns null
*/
public function getAccessToken($sessionId);
/**
* Validate a refresh token
* @param string $refreshToken The refresh token
* @param string $clientId The client ID
* @return int The session ID
*/
public function validateRefreshToken($refreshToken, $clientId);
/**
* Update the refresh token
*
* Example SQL query:
*
* <code>
* UPDATE oauth_sessions SET access_token = $newAccessToken, refresh_token =
* $newRefreshToken, access_toke_expires = $accessTokenExpires, last_updated = UNIX_TIMESTAMP(NOW()) WHERE
* id = $sessionId
* </code>
*
* @param string $sessionId The session ID
* @param string $newAccessToken The new access token for this session
* @param string $newRefreshToken The new refresh token for the session
* @param int $accessTokenExpires The UNIX timestamp of when the new token expires
* @return void
*/
public function updateRefreshToken(
$sessionId,
$newAccessToken,
$newRefreshToken,
$accessTokenExpires
);
/**
* Associates a session with a scope
*
* Example SQL query:
*
* <code>
* INSERT INTO oauth_session_scopes (session_id, scope_id) VALUE ($sessionId,
* $scopeId)
* </code>
*
* @param int $sessionId The session ID
* @param string $scopeId The scope ID
* @return void
*/
public function associateScope($sessionId, $scopeId);
/**
* Return the scopes associated with an access token
*
* Example SQL query:
*
* <code>
* SELECT oauth_scopes.scope FROM oauth_session_scopes JOIN oauth_scopes ON
* oauth_session_scopes.scope_id = oauth_scopes.id WHERE
* session_id = $sessionId
* </code>
*
* Response:
*
* <code>
* Array
* (
* [0] => (string) The scope
* [1] => (string) The scope
* [2] => (string) The scope
* ...
* ...
* )
* </code>
*
* @param int $sessionId The session ID
* @return array
*/
public function getScopes($sessionId);
}

View File

@@ -0,0 +1,412 @@
<?php
use \Mockery as m;
class Auth_Code_Grant_Test extends PHPUnit_Framework_TestCase
{
private $client;
private $session;
private $scope;
public function setUp()
{
$this->client = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$this->scope = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
}
private function returnDefault()
{
return new League\OAuth2\Server\Authorization($this->client, $this->session, $this->scope);
}
public function test_setAuthTokenTTL()
{
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\AuthCode($a);
$grant->setAuthTokenTTL(30);
$reflector = new ReflectionClass($grant);
$requestProperty = $reflector->getProperty('authTokenTTL');
$requestProperty->setAccessible(true);
$v = $requestProperty->getValue($grant);
$this->assertEquals(30, $v);
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noClientId()
{
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$g->checkAuthoriseParams();
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noRedirectUri()
{
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$g->checkAuthoriseParams(array(
'client_id' => 1234
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noRequiredState()
{
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->requireStateParam(true);
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_checkAuthoriseParams_badClient()
{
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_missingResponseType()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 3
*/
public function test_checkAuthoriseParams_badResponseType()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'foo'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_missingScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$a->requireScopeParam(true);
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => ''
));
}
public function test_checkAuthoriseParams_defaultScope()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$a->setDefaultScope('test.scope');
$a->requireScopeParam(false);
$params = $g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => ''
));
$this->assertArrayHasKey('scopes', $params);
$this->assertEquals(1, count($params['scopes']));
}
public function test_checkAuthoriseParams_defaultScopeArray()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$a->setDefaultScope(array('test.scope', 'test.scope2'));
$a->requireScopeParam(false);
$params = $g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => ''
));
$this->assertArrayHasKey('scopes', $params);
$this->assertEquals(2, count($params['scopes']));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 4
*/
public function test_checkAuthoriseParams_badScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(false);
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => 'foo'
));
}
public function test_checkAuthoriseParams_passedInput()
{
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$v = $g->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => 'foo',
'state' => 'xyz'
));
$this->assertEquals(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
),
'scope' => 'foo',
'state' => 'xyz'
), $v);
}
public function test_checkAuthoriseParams()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$_GET['client_id'] = 1234;
$_GET['redirect_uri'] = 'http://foo/redirect';
$_GET['response_type'] = 'code';
$_GET['scope'] = 'foo';
$_GET['state'] = 'xyz';
$request = new League\OAuth2\Server\Util\Request($_GET);
$a->setRequest($request);
$v = $g->checkAuthoriseParams();
$this->assertEquals(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
),
'scope' => 'foo',
'state' => 'xyz'
), $v);
}
function test_newAuthoriseRequest()
{
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateRedirectUri')->andReturn(null);
$this->session->shouldReceive('associateAuthCode')->andReturn(1);
$this->session->shouldReceive('associateAuthCodeScope')->andReturn(null);
$a = $this->returnDefault();
$g = new League\OAuth2\Server\Grant\AuthCode($a);
$a->addGrantType($g);
$params = array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
)
);
$v = $g->newAuthoriseRequest('user', 123, $params);
$this->assertEquals(40, strlen($v));
}
}

View File

@@ -10,14 +10,14 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function setUp()
{
$this->client = M::mock('OAuth2\Storage\ClientInterface');
$this->session = M::mock('OAuth2\Storage\SessionInterface');
$this->scope = M::mock('OAuth2\Storage\ScopeInterface');
$this->client = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$this->scope = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
}
private function returnDefault()
{
return new OAuth2\AuthServer($this->client, $this->session, $this->scope);
return new League\OAuth2\Server\Authorization($this->client, $this->session, $this->scope);
}
/**
@@ -25,17 +25,17 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
*/
public function test__construct_NoStorage()
{
$a = new OAuth2\AuthServer;
new League\OAuth2\Server\Authorization;
}
public function test__contruct_WithStorage()
{
$a = $this->returnDefault();
$this->returnDefault();
}
public function test_getExceptionMessage()
{
$m = OAuth2\AuthServer::getExceptionMessage('access_denied');
$m = League\OAuth2\Server\Authorization::getExceptionMessage('access_denied');
$reflector = new ReflectionClass($this->returnDefault());
$exceptionMessages = $reflector->getProperty('exceptionMessages');
@@ -47,46 +47,55 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_getExceptionCode()
{
$this->assertEquals('access_denied', OAuth2\AuthServer::getExceptionType(2));
$this->assertEquals('access_denied', League\OAuth2\Server\Authorization::getExceptionType(2));
}
public function test_getExceptionHttpHeaders()
{
$this->assertEquals(array('HTTP/1.1 401 Unauthorized'), League\OAuth2\Server\Authorization::getExceptionHttpHeaders('access_denied'));
$this->assertEquals(array('HTTP/1.1 500 Internal Server Error'), League\OAuth2\Server\Authorization::getExceptionHttpHeaders('server_error'));
$this->assertEquals(array('HTTP/1.1 501 Not Implemented'), League\OAuth2\Server\Authorization::getExceptionHttpHeaders('unsupported_grant_type'));
$this->assertEquals(array('HTTP/1.1 400 Bad Request'), League\OAuth2\Server\Authorization::getExceptionHttpHeaders('invalid_refresh'));
}
public function test_hasGrantType()
{
$this->assertFalse(OAuth2\AuthServer::hasGrantType('test'));
$a = $this->returnDefault();
$this->assertFalse($a->hasGrantType('test'));
}
public function test_addGrantType()
{
$a = $this->returnDefault();
$grant = M::mock('OAuth2\Grant\GrantTypeInterface');
$grant = M::mock('League\OAuth2\Server\Grant\GrantTypeInterface');
$grant->shouldReceive('getResponseType')->andReturn('test');
$a->addGrantType($grant, 'test');
$this->assertTrue(OAuth2\AuthServer::hasGrantType('test'));
$this->assertTrue($a->hasGrantType('test'));
}
public function test_addGrantType_noIdentifier()
{
$a = $this->returnDefault();
$grant = M::mock('OAuth2\Grant\GrantTypeInterface');
$grant = M::mock('League\OAuth2\Server\Grant\GrantTypeInterface');
$grant->shouldReceive('getIdentifier')->andReturn('test');
$grant->shouldReceive('getResponseType')->andReturn('test');
$a->addGrantType($grant);
$this->assertTrue(OAuth2\AuthServer::hasGrantType('test'));
$this->assertTrue($a->hasGrantType('test'));
}
public function test_getScopeDelimeter()
{
$a = $this->returnDefault();
$this->assertEquals(',', $a->getScopeDelimeter());
$this->assertEquals(' ', $a->getScopeDelimeter());
}
public function test_setScopeDelimeter()
{
$a = $this->returnDefault();
$a->setScopeDelimeter(';');
$this->assertEquals(';', $a->getScopeDelimeter());
$a->setScopeDelimeter(',');
$this->assertEquals(',', $a->getScopeDelimeter());
}
public function test_requireScopeParam()
@@ -102,6 +111,34 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertFalse($v);
}
public function test_scopeParamRequired()
{
$a = $this->returnDefault();
$a->requireScopeParam(false);
$this->assertFalse($a->scopeParamRequired());
}
public function test_setDefaultScope()
{
$a = $this->returnDefault();
$a->setDefaultScope('test.default');
$reflector = new ReflectionClass($a);
$requestProperty = $reflector->getProperty('defaultScope');
$requestProperty->setAccessible(true);
$v = $requestProperty->getValue($a);
$this->assertEquals('test.default', $v);
}
public function test_getDefaultScope()
{
$a = $this->returnDefault();
$a->setDefaultScope('test.default');
$this->assertEquals('test.default', $a->getDefaultScope());
}
public function test_requireStateParam()
{
$a = $this->returnDefault();
@@ -115,14 +152,14 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertTrue($v);
}
public function test_getExpiresIn()
public function test_getAccessTokenTTL()
{
$a = $this->returnDefault();
$a->setExpiresIn(7200);
$this->assertEquals(7200, $a::getExpiresIn());
$a->setAccessTokenTTL(7200);
$this->assertEquals(7200, $a->getAccessTokenTTL());
}
public function test_setExpiresIn()
public function test_setAccessTokenTTL()
{
$a = $this->returnDefault();
$a->setScopeDelimeter(';');
@@ -132,301 +169,37 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
public function test_setRequest()
{
$a = $this->returnDefault();
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$a->setRequest($request);
$reflector = new ReflectionClass($a);
$requestProperty = $reflector->getProperty('request');
$requestProperty->setAccessible(true);
$v = $requestProperty->getValue();
$v = $requestProperty->getValue($a);
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
$this->assertTrue($v instanceof League\OAuth2\Server\Util\RequestInterface);
}
public function test_getRequest()
{
$a = $this->returnDefault();
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$a->setRequest($request);
$v = $a::getRequest();
$v = $a->getRequest();
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
$this->assertTrue($v instanceof League\OAuth2\Server\Util\RequestInterface);
}
public function test_getStorage()
{
$a = $this->returnDefault();
$this->assertTrue($a->getStorage('session') instanceof OAuth2\Storage\SessionInterface);
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noClientId()
{
$a = $this->returnDefault();
$a->checkAuthoriseParams();
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_noRedirectUri()
{
$a = $this->returnDefault();
$a->checkAuthoriseParams(array(
'client_id' => 1234
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_checkAuthoriseParams_badClient()
{
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_missingResponseType()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 3
*/
public function test_checkAuthoriseParams_badResponseType()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'foo'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_checkAuthoriseParams_missingScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => ''
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedExceptionCode 4
*/
public function test_checkAuthoriseParams_badScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => 'foo'
));
}
public function test_checkAuthoriseParams_passedInput()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$v = $a->checkAuthoriseParams(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'response_type' => 'code',
'scope' => 'foo',
'state' => 'xyz'
));
$this->assertEquals(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
),
'scope' => 'foo',
'state' => 'xyz'
), $v);
}
public function test_checkAuthoriseParams()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$_GET['client_id'] = 1234;
$_GET['redirect_uri'] = 'http://foo/redirect';
$_GET['response_type'] = 'code';
$_GET['scope'] = 'foo';
$_GET['state'] = 'xyz';
$request = new OAuth2\Util\Request($_GET);
$a->setRequest($request);
$v = $a->checkAuthoriseParams();
$this->assertEquals(array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
),
'scope' => 'foo',
'state' => 'xyz'
), $v);
}
function test_newAuthoriseRequest()
{
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$params = array(
'client_id' => 1234,
'redirect_uri' => 'http://foo/redirect',
'client_details' => array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
),
'response_type' => 'code',
'scopes' => array(
array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
)
)
);
$v = $a->newAuthoriseRequest('user', 123, $params);
$this->assertEquals(40, strlen($v));
$this->assertTrue($a->getStorage('session') instanceof League\OAuth2\Server\Storage\SessionInterface);
}
public function test_getGrantType()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$reflector = new ReflectionClass($a);
$method = $reflector->getMethod('getGrantType');
@@ -434,72 +207,82 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$result = $method->invoke($a, 'authorization_code');
$this->assertTrue($result instanceof OAuth2\Grant\GrantTypeInterface);
$this->assertTrue($result instanceof League\OAuth2\Server\Grant\GrantTypeInterface);
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\InvalidGrantTypeException
* @expectedExceptionCode 9
*/
public function test_getGrantType_fail()
{
$a = $this->returnDefault();
$a->getGrantType('blah');
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingGrantType()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken();
$a->issueAccessToken();
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 7
*/
public function test_issueAccessToken_badGrantType()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array('grant_type' => 'foo'));
$a->issueAccessToken(array('grant_type' => 'foo'));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingClientId()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingClientSecret()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code',
'client_id' => 1234
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingRedirectUri()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code',
'client_id' => 1234,
'client_secret' => 5678
@@ -507,7 +290,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_issueAccessToken_badClient()
@@ -515,9 +298,9 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code',
'client_id' => 1234,
'client_secret' => 5678,
@@ -526,7 +309,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_missingCode()
@@ -534,9 +317,9 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(array());
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code',
'client_id' => 1234,
'client_secret' => 5678,
@@ -545,7 +328,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 9
*/
public function test_issueAccessToken_badCode()
@@ -554,9 +337,9 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'authorization_code',
'client_id' => 1234,
'client_secret' => 5678,
@@ -574,11 +357,18 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
'name' => 'Example Client'
));
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(array(
'session_id' => 1,
'authcode_id' => 1
));
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('removeAuthCode')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('getAuthCodeScopes')->andReturn(array('scope_id' => 1));
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$v = $a->issueAccessToken(array(
'grant_type' => 'authorization_code',
@@ -593,8 +383,8 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function test_issueAccessToken()
@@ -608,9 +398,13 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('removeAuthCode')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('getAuthCodeScopes')->andReturn(array('scope_id' => 1));
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$_POST['grant_type'] = 'authorization_code';
$_POST['client_id'] = 1234;
@@ -618,7 +412,7 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$_POST['redirect_uri'] = 'http://foo/redirect';
$_POST['code'] = 'foobar';
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -628,8 +422,90 @@ class Authorization_Server_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function test_issueAccessToken_customExpiresIn()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('removeAuthCode')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('getAuthCodeScopes')->andReturn(array('scope_id' => 1));
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\AuthCode($a);
$grant->setAccessTokenTTL(30);
$a->addGrantType($grant);
$_POST['grant_type'] = 'authorization_code';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$_POST['redirect_uri'] = 'http://foo/redirect';
$_POST['code'] = 'foobar';
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertNotEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertNotEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
$this->assertEquals(30, $v['expires_in']);
$this->assertEquals(time()+30, $v['expires']);
}
public function test_issueAccessToken_HTTP_auth()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('removeAuthCode')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('getAuthCodeScopes')->andReturn(array('scope_id' => 1));
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$_POST['grant_type'] = 'authorization_code';
$_SERVER['PHP_AUTH_USER'] = 1234;
$_SERVER['PHP_AUTH_PW'] = 5678;
$_POST['redirect_uri'] = 'http://foo/redirect';
$_POST['code'] = 'foobar';
$request = new League\OAuth2\Server\Util\Request(array(), $_POST, array(), array(), $_SERVER);
$a->setRequest($request);
$v = $a->issueAccessToken();
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function tearDown() {

View File

@@ -10,53 +10,53 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
public function setUp()
{
$this->client = M::mock('OAuth2\Storage\ClientInterface');
$this->session = M::mock('OAuth2\Storage\SessionInterface');
$this->scope = M::mock('OAuth2\Storage\ScopeInterface');
$this->client = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$this->scope = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
}
private function returnDefault()
{
return new OAuth2\AuthServer($this->client, $this->session, $this->scope);
return new League\OAuth2\Server\Authorization($this->client, $this->session, $this->scope);
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_clientCredentialsGrant_missingClientId()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'client_credentials'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_clientCredentialsGrant_missingClientPassword()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_issueAccessToken_clientCredentialsGrant_badClient()
@@ -64,18 +64,200 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_clientCredentialsGrant_missingScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(true);
$a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678
));
}
public function test_issueAccessToken_clientCredentialsGrant_defaultScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'key' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(false);
$a->setDefaultScope('foobar');
$v = $a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678,
'scope' => ''
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
public function test_issueAccessToken_clientCredentialsGrant_defaultScopeArray()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'key' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(false);
$a->setDefaultScope(array('foobar', 'barfoo'));
$v = $a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678,
'scope' => ''
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 4
*/
public function test_issueAccessToken_clientCredentialsGrant_badScope()
{
$this->scope->shouldReceive('getScope')->andReturn(false);
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678,
'scope' => 'blah'
));
}
public function test_issueAccessToken_clientCredentialsGrant_goodScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'key' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$v = $a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678,
'scope' => 'blah'
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
function test_issueAccessToken_clientCredentialsGrant_passedInput()
{
$this->client->shouldReceive('getClient')->andReturn(array(
@@ -90,15 +272,16 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(false);
$v = $a->issueAccessToken(array(
'grant_type' => 'client_credentials',
'client_id' => 1234,
'client_secret' => 5678
'client_secret' => 5678,
));
$this->assertArrayHasKey('access_token', $v);
@@ -106,8 +289,8 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
function test_issueAccessToken_clientCredentialsGrant()
@@ -124,16 +307,17 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(false);
$_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -143,8 +327,50 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
function test_issueAccessToken_clientCredentialsGrant_customExpiresIn()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\ClientCredentials($a);
$grant->setAccessTokenTTL(30);
$a->addGrantType($grant);
$a->requireScopeParam(false);
$_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertNotEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertNotEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
$this->assertEquals(30, $v['expires_in']);
$this->assertEquals(time()+30, $v['expires']);
}
function test_issueAccessToken_clientCredentialsGrant_withRefreshToken()
@@ -161,17 +387,17 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\ClientCredentials());
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials($a));
$a->requireScopeParam(false);
$_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -180,10 +406,9 @@ class Client_Credentials_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
}

View File

@@ -10,53 +10,53 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
public function setUp()
{
$this->client = M::mock('OAuth2\Storage\ClientInterface');
$this->session = M::mock('OAuth2\Storage\SessionInterface');
$this->scope = M::mock('OAuth2\Storage\ScopeInterface');
$this->client = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$this->scope = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
}
private function returnDefault()
{
return new OAuth2\AuthServer($this->client, $this->session, $this->scope);
return new League\OAuth2\Server\Authorization($this->client, $this->session, $this->scope);
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_passwordGrant_missingClientId()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password());
$a->addGrantType(new League\OAuth2\Server\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_passwordGrant_missingClientPassword()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password());
$a->addGrantType(new League\OAuth2\Server\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_issueAccessToken_passwordGrant_badClient()
@@ -64,12 +64,12 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\Password());
$a->addGrantType(new League\OAuth2\Server\Grant\Password($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678
@@ -77,7 +77,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\InvalidGrantTypeException
* @expectedException League\OAuth2\Server\Exception\InvalidGrantTypeException
*/
function test_issueAccessToken_passwordGrant_invalidCallback()
{
@@ -98,11 +98,11 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$testCredentials = null;
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
@@ -112,7 +112,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
function test_issueAccessToken_passwordGrant_missingUsername()
@@ -131,14 +131,14 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function($u, $p) { return false; };
$testCredentials = function() { return false; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678
@@ -146,7 +146,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
function test_issueAccessToken_passwordGrant_missingPassword()
@@ -165,14 +165,14 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function($u, $p) { return false; };
$testCredentials = function() { return false; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
@@ -181,7 +181,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
function test_issueAccessToken_passwordGrant_badCredentials()
@@ -200,10 +200,220 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function($u, $p) { return false; };
$testCredentials = function() { return false; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 4
*/
public function test_issueAccessToken_passwordGrant_badScopes()
{
$this->scope->shouldReceive('getScope')->andReturn(false);
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => 'blah'
));
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_passwordGrant_missingScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(true);
$a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar'
));
}
public function test_issueAccessToken_passwordGrant_defaultScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(false);
$a->setDefaultScope('foobar');
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => ''
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
public function test_issueAccessToken_passwordGrant_defaultScopeArray()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(false);
$a->setDefaultScope(array('foobar', 'barfoo'));
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar',
'scope' => ''
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
public function test_issueAccessToken_passwordGrant_goodScope()
{
$this->scope->shouldReceive('getScope')->andReturn(array(
'id' => 1,
'scope' => 'foo',
'name' => 'Foo Name',
'description' => 'Foo Name Description'
));
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
@@ -211,9 +421,15 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
'grant_type' => 'password',
'client_id' => 1234,
'client_secret' => 5678,
'username' => 'foo',
'password' => 'bar'
'username' => 'foo',
'password' => 'bar',
'scope' => 'blah'
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
}
function test_issueAccessToken_passwordGrant_passedInput()
@@ -231,13 +447,15 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function($u, $p) { return 1; };
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(false);
$v = $a->issueAccessToken(array(
'grant_type' => 'password',
@@ -252,8 +470,8 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
function test_issueAccessToken_passwordGrant()
@@ -271,13 +489,15 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function($u, $p) { return 1; };
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->requireScopeParam(false);
$_POST['grant_type'] = 'password';
$_POST['client_id'] = 1234;
@@ -285,7 +505,7 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$_POST['username'] = 'foo';
$_POST['password'] = 'bar';
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -295,11 +515,11 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
function test_issueAccessToken_passwordGrant_withRefreshToken()
function test_issueAccessToken_passwordGrant_customExpiresIn()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
@@ -314,14 +534,16 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$testCredentials = function($u, $p) { return 1; };
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new OAuth2\Grant\Password();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$pgrant->setAccessTokenTTL(30);
$a->addGrantType($pgrant);
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->requireScopeParam(false);
$_POST['grant_type'] = 'password';
$_POST['client_id'] = 1234;
@@ -329,7 +551,55 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$_POST['username'] = 'foo';
$_POST['password'] = 'bar';
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertNotEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertNotEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
$this->assertEquals(30, $v['expires_in']);
$this->assertEquals(time()+30, $v['expires']);
}
function test_issueAccessToken_passwordGrant_withRefreshToken()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('createSession')->andReturn(1);
$this->session->shouldReceive('deleteSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(null);
$testCredentials = function() { return 1; };
$a = $this->returnDefault();
$pgrant = new League\OAuth2\Server\Grant\Password($a);
$pgrant->setVerifyCredentialsCallback($testCredentials);
$a->addGrantType($pgrant);
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$a->requireScopeParam(false);
$_POST['grant_type'] = 'password';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$_POST['username'] = 'foo';
$_POST['password'] = 'bar';
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -340,8 +610,8 @@ class Password_Grant_Test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
}

View File

@@ -10,14 +10,22 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
public function setUp()
{
$this->client = M::mock('OAuth2\Storage\ClientInterface');
$this->session = M::mock('OAuth2\Storage\SessionInterface');
$this->scope = M::mock('OAuth2\Storage\ScopeInterface');
$this->client = M::mock('League\OAuth2\Server\Storage\ClientInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
$this->scope = M::mock('League\OAuth2\Server\Storage\ScopeInterface');
}
private function returnDefault()
{
return new OAuth2\AuthServer($this->client, $this->session, $this->scope);
return new League\OAuth2\Server\Authorization($this->client, $this->session, $this->scope);
}
public function test_setRefreshTokenTTL()
{
$a = $this->returnDefault();
$rt = new League\OAuth2\Server\Grant\RefreshToken($a);
$rt->setRefreshTokenTTL(30);
$this->assertEquals(30, $rt->getRefreshTokenTTL());
}
public function test_issueAccessToken_with_refresh_token()
@@ -31,10 +39,15 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('removeAuthCode')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->session->shouldReceive('getAuthCodeScopes')->andReturn(array('scope_id' => 1));
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\AuthCode());
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\AuthCode($a));
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$_POST['grant_type'] = 'authorization_code';
$_POST['client_id'] = 1234;
@@ -42,7 +55,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$_POST['redirect_uri'] = 'http://foo/redirect';
$_POST['code'] = 'foobar';
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -53,47 +66,47 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_refreshTokenGrant_missingClientId()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'refresh_token'
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_refreshTokenGrant_missingClientSecret()
{
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 8
*/
public function test_issueAccessToken_refreshTokenGrant_badClient()
@@ -101,12 +114,12 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678
@@ -114,7 +127,7 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_refreshTokenGrant_missingRefreshToken()
@@ -122,35 +135,34 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->client->shouldReceive('getClient')->andReturn(array());
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
//'refresh_token' =>
'client_secret' => 5678
));
}
/**
* @expectedException OAuth2\Exception\ClientException
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_refreshTokenGrant_badRefreshToken()
{
$this->client->shouldReceive('getClient')->andReturn(array());
$this->client->shouldReceive('validateRefreshToken')->andReturn(false);
$this->session->shouldReceive('validateRefreshToken')->andReturn(false);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken(array(
$a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
@@ -167,21 +179,25 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array());
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$_POST['grant_type'] = 'refresh_token';
$_POST['client_id'] = 1234;
$_POST['client_secret'] = 5678;
$_POST['refresh_token'] = 'abcdef';
$request = new OAuth2\Util\Request(array(), $_POST);
$request = new League\OAuth2\Server\Util\Request(array(), $_POST);
$a->setRequest($request);
$v = $a->issueAccessToken();
@@ -190,10 +206,9 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function test_issueAccessToken_refreshTokenGrant()
@@ -205,14 +220,61 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
'name' => 'Example Client'
));
$this->client->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array('id' => 1));
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$a->addGrantType(new OAuth2\Grant\RefreshToken());
$a->addGrantType(new League\OAuth2\Server\Grant\RefreshToken($a));
$v = $a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
'refresh_token' => 'abcdef',
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function test_issueAccessToken_refreshTokenGrant_rotateTokens()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array('id' => 1));
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$rt = new League\OAuth2\Server\Grant\RefreshToken($a);
$rt->rotateRefreshTokens(true);
$a->addGrantType($rt);
$v = $a->issueAccessToken(array(
'grant_type' => 'refresh_token',
@@ -227,7 +289,137 @@ class Refresh_Token_test extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertEquals($a::getExpiresIn(), $v['expires_in']);
$this->assertEquals(time()+$a::getExpiresIn(), $v['expires']);
$this->assertEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
}
public function test_issueAccessToken_refreshTokenGrant_customExpiresIn()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array('id' => 1));
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\RefreshToken($a);
$grant->setAccessTokenTTL(30);
$a->addGrantType($grant);
$v = $a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
'refresh_token' => 'abcdef',
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertNotEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertNotEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
$this->assertEquals(30, $v['expires_in']);
$this->assertEquals(time()+30, $v['expires']);
}
public function test_issueAccessToken_refreshTokenGrant_newScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array(array('id' => 1, 'scope' => 'foo'), array('id' => 2, 'scope' => 'bar')));
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->scope->shouldReceive('getScope')->andReturn(array('id' => 1, 'scope' => 'foo'));
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\RefreshToken($a);
$grant->setAccessTokenTTL(30);
$grant->rotateRefreshTokens(true);
$a->addGrantType($grant);
$v = $a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
'refresh_token' => 'abcdef',
'scope' => 'foo'
));
$this->assertArrayHasKey('access_token', $v);
$this->assertArrayHasKey('token_type', $v);
$this->assertArrayHasKey('expires', $v);
$this->assertArrayHasKey('expires_in', $v);
$this->assertArrayHasKey('refresh_token', $v);
$this->assertNotEquals($a->getAccessTokenTTL(), $v['expires_in']);
$this->assertNotEquals(time()+$a->getAccessTokenTTL(), $v['expires']);
$this->assertEquals(30, $v['expires_in']);
$this->assertEquals(time()+30, $v['expires']);
}
/**
* @expectedException League\OAuth2\Server\Exception\ClientException
* @expectedExceptionCode 0
*/
public function test_issueAccessToken_refreshTokenGrant_badNewScopes()
{
$this->client->shouldReceive('getClient')->andReturn(array(
'client_id' => 1234,
'client_secret' => 5678,
'redirect_uri' => 'http://foo/redirect',
'name' => 'Example Client'
));
$this->session->shouldReceive('validateRefreshToken')->andReturn(1);
$this->session->shouldReceive('validateAuthCode')->andReturn(1);
$this->session->shouldReceive('updateSession')->andReturn(null);
$this->session->shouldReceive('updateRefreshToken')->andReturn(null);
$this->session->shouldReceive('getAccessToken')->andReturn(null);
$this->session->shouldReceive('getScopes')->andReturn(array(array('id' => 1, 'scope' => 'foo'), array('id' => 2, 'scope' => 'bar')));
$this->session->shouldReceive('associateAccessToken')->andReturn(1);
$this->session->shouldReceive('associateRefreshToken')->andReturn(1);
$this->session->shouldReceive('removeRefreshToken')->andReturn(1);
$this->session->shouldReceive('associateScope')->andReturn(null);
$this->scope->shouldReceive('getScope')->andReturn(array('id' => 1, 'scope' => 'foo'));
$a = $this->returnDefault();
$grant = new League\OAuth2\Server\Grant\RefreshToken($a);
$grant->setAccessTokenTTL(30);
$grant->rotateRefreshTokens(true);
$a->addGrantType($grant);
$a->issueAccessToken(array(
'grant_type' => 'refresh_token',
'client_id' => 1234,
'client_secret' => 5678,
'refresh_token' => 'abcdef',
'scope' => 'foobar'
));
}
}

View File

@@ -8,18 +8,18 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
public function setUp()
{
$this->session = M::mock('OAuth2\Storage\SessionInterface');
$this->session = M::mock('League\OAuth2\Server\Storage\SessionInterface');
}
private function returnDefault()
{
return new OAuth2\ResourceServer($this->session);
return new League\OAuth2\Server\Resource($this->session);
}
public function test_setRequest()
{
$s = $this->returnDefault();
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$s->setRequest($request);
$reflector = new ReflectionClass($s);
@@ -27,17 +27,17 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$requestProperty->setAccessible(true);
$v = $requestProperty->getValue($s);
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
$this->assertTrue($v instanceof League\OAuth2\Server\Util\RequestInterface);
}
public function test_getRequest()
{
$s = $this->returnDefault();
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$s->setRequest($request);
$v = $s->getRequest();
$this->assertTrue($v instanceof OAuth2\Util\RequestInterface);
$this->assertTrue($v instanceof League\OAuth2\Server\Util\RequestInterface);
}
public function test_getTokenKey()
@@ -59,13 +59,19 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$this->assertEquals('oauth_token', $v);
}
public function test_getScopes()
{
$s = $this->returnDefault();
$this->assertEquals(array(), $s->getScopes());
}
/**
* @expectedException OAuth2\Exception\InvalidAccessTokenException
* @expectedException League\OAuth2\Server\Exception\InvalidAccessTokenException
*/
public function test_determineAccessToken_missingToken()
{
$_SERVER['HTTP_AUTHORIZATION'] = 'Bearer';
$request = new OAuth2\Util\Request(array(), array(), array(), array(), $_SERVER);
$request = new League\OAuth2\Server\Util\Request(array(), array(), array(), array(), $_SERVER);
$s = $this->returnDefault();
$s->setRequest($request);
@@ -74,18 +80,36 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$method = $reflector->getMethod('determineAccessToken');
$method->setAccessible(true);
$result = $method->invoke($s);
$method->invoke($s);
}
/**
* @expectedException League\OAuth2\Server\Exception\InvalidAccessTokenException
*/
public function test_determineAccessToken_brokenCurlRequest()
{
$_SERVER['HTTP_AUTHORIZATION'] = 'Bearer, Bearer abcdef';
$request = new League\OAuth2\Server\Util\Request(array(), array(), array(), array(), $_SERVER);
$s = $this->returnDefault();
$s->setRequest($request);
$reflector = new ReflectionClass($s);
$method = $reflector->getMethod('determineAccessToken');
$method->setAccessible(true);
$method->invoke($s);
}
public function test_determineAccessToken_fromHeader()
{
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$requestReflector = new ReflectionClass($request);
$param = $requestReflector->getProperty('headers');
$param->setAccessible(true);
$param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm'
'Authorization' => 'Bearer abcdef'
));
$s = $this->returnDefault();
$s->setRequest($request);
@@ -100,6 +124,29 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$this->assertEquals('abcdef', $result);
}
public function test_determineAccessToken_fromBrokenCurlHeader()
{
$request = new League\OAuth2\Server\Util\Request();
$requestReflector = new ReflectionClass($request);
$param = $requestReflector->getProperty('headers');
$param->setAccessible(true);
$param->setValue($request, array(
'Authorization' => 'Bearer abcdef, Bearer abcdef'
));
$s = $this->returnDefault();
$s->setRequest($request);
$reflector = new ReflectionClass($s);
$method = $reflector->getMethod('determineAccessToken');
$method->setAccessible(true);
$result = $method->invoke($s);
$this->assertEquals('abcdef', $result);
}
public function test_determineAccessToken_fromMethod()
{
$s = $this->returnDefault();
@@ -107,7 +154,7 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$_GET[$s->getTokenKey()] = 'abcdef';
$_SERVER['REQUEST_METHOD'] = 'get';
$request = new OAuth2\Util\Request($_GET, array(), array(), array(), $_SERVER);
$request = new League\OAuth2\Server\Util\Request($_GET, array(), array(), array(), $_SERVER);
$s->setRequest($request);
$reflector = new ReflectionClass($s);
@@ -120,18 +167,18 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
}
/**
* @expectedException OAuth2\Exception\InvalidAccessTokenException
* @expectedException League\OAuth2\Server\Exception\InvalidAccessTokenException
*/
public function test_isValid_notValid()
{
$this->session->shouldReceive('validateAccessToken')->andReturn(false);
$request = new OAuth2\Util\Request();
$request = new League\OAuth2\Server\Util\Request();
$requestReflector = new ReflectionClass($request);
$param = $requestReflector->getProperty('headers');
$param->setAccessible(true);
$param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm'
'Authorization' => 'Bearer abcdef'
));
$s = $this->returnDefault();
$s->setRequest($request);
@@ -142,19 +189,25 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
public function test_isValid_valid()
{
$this->session->shouldReceive('validateAccessToken')->andReturn(array(
'id' => 1,
'owner_type' => 'user',
'owner_id' => 123
'session_id' => 1,
'owner_type' => 'user',
'owner_id' => 123,
'client_id' => 'testapp'
));
$this->session->shouldReceive('getScopes')->andReturn(array('foo', 'bar'));
$request = new OAuth2\Util\Request();
$this->session->shouldReceive('getScopes')->andReturn(array(
array('key' => 'foo'),
array('key' => 'bar')
));
$request = new League\OAuth2\Server\Util\Request();
$requestReflector = new ReflectionClass($request);
$param = $requestReflector->getProperty('headers');
$param->setAccessible(true);
$param->setValue($request, array(
'Authorization' => 'Bearer YWJjZGVm'
'Authorization' => 'Bearer abcdef'
));
$s = $this->returnDefault();
$s->setRequest($request);
@@ -162,6 +215,7 @@ class Resource_Server_test extends PHPUnit_Framework_TestCase
$this->assertEquals(123, $s->getOwnerId());
$this->assertEquals('user', $s->getOwnerType());
$this->assertEquals('abcdef', $s->getAccessToken());
$this->assertEquals('testapp', $s->getClientId());
$this->assertTrue($s->hasScope('foo'));
$this->assertTrue($s->hasScope('bar'));
$this->assertTrue($s->hasScope(array('foo', 'bar')));

View File

@@ -4,9 +4,9 @@ class RedirectUri_test extends PHPUnit_Framework_TestCase
{
function test_make()
{
$v1 = OAuth2\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar'));
$v2 = OAuth2\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar'), '#');
$v3 = OAuth2\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar', 'bar' => 'foo'));
$v1 = League\OAuth2\Server\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar'));
$v2 = League\OAuth2\Server\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar'), '#');
$v3 = League\OAuth2\Server\Util\RedirectUri::make('https://foobar/', array('foo'=>'bar', 'bar' => 'foo'));
$this->assertEquals('https://foobar/?foo=bar', $v1);
$this->assertEquals('https://foobar/#foo=bar', $v2);

View File

@@ -6,7 +6,7 @@ class Request_test extends PHPUnit_Framework_TestCase
function setUp()
{
$this->request = new OAuth2\Util\Request(
$this->request = new League\OAuth2\Server\Util\Request(
array('foo' => 'bar'),
array('foo' => 'bar'),
array('foo' => 'bar'),
@@ -17,10 +17,10 @@ class Request_test extends PHPUnit_Framework_TestCase
function test_buildFromIndex()
{
$r = new OAuth2\Util\Request();
$r = new League\OAuth2\Server\Util\Request();
$r->buildFromGlobals();
$this->assertTrue($r instanceof OAuth2\Util\Request);
$this->assertTrue($r instanceof League\OAuth2\Server\Util\Request);
}
function test_get()
@@ -68,6 +68,6 @@ class Request_test extends PHPUnit_Framework_TestCase
$method = $reflector->getMethod('getPropertyValue');
$method->setAccessible(true);
$result = $method->invoke($this->request, 'blah');
$method->invoke($this->request, 'blah');
}
}

View File

@@ -4,9 +4,9 @@ class Secure_Key_test extends PHPUnit_Framework_TestCase
{
function test_make()
{
$v1 = OAuth2\Util\SecureKey::make();
$v2 = OAuth2\Util\SecureKey::make();
$v3 = OAuth2\Util\SecureKey::make(50);
$v1 = League\OAuth2\Server\Util\SecureKey::make();
$v2 = League\OAuth2\Server\Util\SecureKey::make();
$v3 = League\OAuth2\Server\Util\SecureKey::make(50);
$this->assertEquals(40, strlen($v1));
$this->assertTrue($v1 !== $v2);