-
Notifications
You must be signed in to change notification settings - Fork 3
/
endpoint.php
275 lines (243 loc) · 9.17 KB
/
endpoint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
/**
* EGroupware OpenID Connect / OAuth2 server
*
* @link https://www.egroupware.org
* @author Ralf Becker <rb-At-egroupware.org>
* @package openid
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
*
* Based on the following MIT Licensed packages:
* @link https://github.com/steverhoades/oauth2-openid-connect-server
* @author Alex Bilbie <[email protected]>
* @copyright Copyright (c) Alex Bilbie
* @link https://github.com/thephpleague/oauth2-server
*/
// until #925 is merged: use League\OAuth2\Server\AuthorizationServer;
use EGroupware\OpenId\AuthorizationServer;
use League\OAuth2\Server\Exception\OAuthServerException;
use EGroupware\OpenId\Grant\AuthCodeGrant;
use EGroupware\OpenId\Grant\ImplicitGrant;
use EGroupware\OpenId\Grant\PasswordGrant;
use EGroupware\OpenId\Grant\RefreshTokenGrant;
use League\OAuth2\Server\Middleware\ResourceServerMiddleware;
use League\OAuth2\Server\ResourceServer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\App;
use Zend\Diactoros\Stream;
use EGroupware\OpenID\ResponseTypes\IdTokenResponse;
use Bnf\Slim3Psr15\CallableResolver;
use EGroupware\OpenID\Repositories\AccessTokenRepository;
use EGroupware\OpenID\Repositories\AuthCodeRepository;
use EGroupware\OpenID\Repositories\ClientRepository;
use EGroupware\OpenID\Repositories\RefreshTokenRepository;
use EGroupware\OpenID\Repositories\UserRepository;
use EGroupware\OpenID\Repositories\IdentityRepository;
use EGroupware\OpenID\Repositories\ScopeRepository;
use EGroupware\OpenID\Entities\UserEntity;
use EGroupware\OpenID\Keys;
use EGroupware\OpenID\Authorize;
use EGroupware\OpenID\Log;
use EGroupware\OpenID\ClaimExtractor;
$GLOBALS['egw_info'] = array(
'flags' => array(
// only /authorize needs a session, /access_token does not
'currentapp' => $_SERVER['PATH_INFO'] === '/authorize' ? 'api' : 'login',
'nonavbar' => True,
'noheader' => True,
'autocreate_session_callback' => Authorize::class.'::anon_session',
));
include('../header.inc.php');
$app = new App([
'settings' => [
'displayErrorDetails' => true,
],
AuthorizationServer::class => function () {
// Init our repositories
$clientRepository = new ClientRepository();
$scopeRepository = new ScopeRepository();
$accessTokenRepository = new AccessTokenRepository();
$authCodeRepository = new AuthCodeRepository();
$refreshTokenRepository = new RefreshTokenRepository();
$keys = new Keys();
// OpenID Connect Response Type
$responseType = new IdTokenResponse(new IdentityRepository(), new ClaimExtractor());
// Setup the authorization server
$server = new AuthorizationServer(
$clientRepository,
$accessTokenRepository,
$scopeRepository,
$keys->getPrivateKey(),
$keys->getEncryptionKey(),
$responseType
);
// Enable the client credentials grant on the server
$server->enableGrantType(
new \League\OAuth2\Server\Grant\ClientCredentialsGrant(),
new \DateInterval(ClientRepository::getDefaultAccessTokenTTL())
);
// Enable the implicit grant on the server with a token TTL of 1 hour
$server->enableGrantType(
new ImplicitGrant(
$authCodeRepository,
new \DateInterval(ClientRepository::getDefaultAuthCodeTTL()),
new \DateInterval(ClientRepository::getDefaultAccessTokenTTL())
)
);
// Enable the authentication code grant on the server
$server->enableGrantType(
new AuthCodeGrant(
$authCodeRepository,
$refreshTokenRepository,
new \DateInterval(ClientRepository::getDefaultAuthCodeTTL())
),
new \DateInterval(ClientRepository::getDefaultAccessTokenTTL())
);
// Enable the password grant on the server with a token TTL of 1 hour
$pwGrant = new PasswordGrant(
new UserRepository(), // instance of UserRepositoryInterface
$refreshTokenRepository
);
$pwGrant->setRefreshTokenTTL(new \DateInterval(ClientRepository::getDefaultRefreshTokenTTL()));
$server->enableGrantType(
$pwGrant,
new \DateInterval(ClientRepository::getDefaultAccessTokenTTL())
);
// Enable the refresh token grant on the server
$refreshGrant = new RefreshTokenGrant($refreshTokenRepository);
$refreshGrant->setRefreshTokenTTL(new \DateInterval(ClientRepository::getDefaultRefreshTokenTTL()));
$server->enableGrantType(
$refreshGrant,
new \DateInterval(ClientRepository::getDefaultAccessTokenTTL())
);
return $server;
},
ResourceServer::class => function () {
$server = new ResourceServer(
new AccessTokenRepository(),
(new Keys())->getPublicKey()
);
return $server;
},
]);
$app->get('/authorize', function (ServerRequestInterface $request, ResponseInterface $response) use ($app)
{
/* @var \League\OAuth2\Server\AuthorizationServer $server */
$server = $app->getContainer()->get(AuthorizationServer::class);
try {
$auth = new Authorize('/openid/'.basename(__FILE__).'/authorize');
// validate does NOT return, before user has approved or denied the request!
$authRequest = $auth->validate($server, $request);
// Return the HTTP redirect response
return $server->completeAuthorizationRequest($authRequest, $response);
}
catch (OAuthServerException $exception) {
return $exception->generateHttpResponse($response);
}
catch (\Exception $exception) {
_egw_log_exception($exception);
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
});
$app->post('/access_token', function (ServerRequestInterface $request, ResponseInterface $response) use ($app)
{
/* @var \League\OAuth2\Server\AuthorizationServer $server */
$server = $app->getContainer()->get(AuthorizationServer::class);
try {
return $server->respondToAccessTokenRequest($request, $response);
}
catch (OAuthServerException $exception) {
return $exception->generateHttpResponse($response);
}
catch (\Exception $exception) {
_egw_log_exception($exception);
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
});
$app->post(
'/introspect',
function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
/* @var \League\OAuth2\Server\AuthorizationServer $server */
$server = $app->getContainer()->get(AuthorizationServer::class);
try {
// Validate the given introspect request
$server->validateIntrospectionRequest($request);
// Try to respond to the introspection request
return $server->respondToIntrospectionRequest($request, $response);
}
catch (OAuthServerException $exception) {
// All instances of OAuthServerException can be converted to a PSR-7 response
return $exception->generateHttpResponse($response);
}
catch (\Exception $exception) {
_egw_log_exception($exception);
$body = $response->getBody();
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
}
);
$app->get('/userinfo', function (ServerRequestInterface $request, ResponseInterface $response)
{
try {
$account_id = $request->getAttribute('oauth_user_id');
$user = new UserEntity($account_id);
$params = ['sub' => $user->getIdentifier()];
$claimExtractor = new ClaimExtractor();
$params += $claimExtractor->extract(
$request->getAttribute('oauth_scopes', []),
$user->getClaims()
);
$response->getBody()->write(json_encode($params));
return $response
->withStatus(200)
->withHeader('pragma', 'no-cache')
->withHeader('cache-control', 'no-store')
->withHeader('content-type', 'application/json; charset=UTF-8');
}
catch (\Exception $exception) {
_egw_log_exception($exception);
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
})->add(new ResourceServerMiddleware($app->getContainer()->get(ResourceServer::class)));
$app->get('/jwks', function (ServerRequestInterface $request, ResponseInterface $response)
{
try
{
$keys = new Keys();
$response->getBody()->write(json_encode(['keys' => [$keys->getJWK()]]));
return $response
->withStatus(200)
->withHeader('content-type', 'application/json; charset=UTF-8');
}
catch (\Exception $exception) {
_egw_log_exception($exception);
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
});
// Slim does NOT detect Authorization header with Apache not writing it to $_SERVER['HTTP_AUTHORIZATION']
if (function_exists('apache_request_headers') && !isset($_SERVER['HTTP_AUTHORIZATION']) &&
($headers = apache_request_headers()) && isset($headers['Authorization']))
{
$_SERVER['HTTP_AUTHORIZATION'] = $headers['Authorization'];
}
// Supply a custom callable resolver for Slim v3, which resolves PSR-15 middlewares
$container = $app->getContainer();
$container['callableResolver'] = function ($container)
{
return new CallableResolver($container);
};
// Add our PSR-15 middleware logger
$formatter = new Log\HttpFormatter();
// create a full request log in "$files/openid/request.log"
$app->add(new Log\Middleware($formatter, $formatter, new Log\Logger('openid')));
$app->run();