forked from hwi/HWIOAuthBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOAuthUtils.php
266 lines (227 loc) · 8.99 KB
/
OAuthUtils.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
<?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HWI\Bundle\OAuthBundle\Security;
use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface;
use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMap;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\HttpUtils;
/**
* OAuthUtils
*
* @author Alexander <[email protected]>
* @author Joseph Bielawski <[email protected]>
* @author Francisco Facioni <[email protected]>
*/
class OAuthUtils
{
const SIGNATURE_METHOD_HMAC = 'HMAC-SHA1';
const SIGNATURE_METHOD_RSA = 'RSA-SHA1';
const SIGNATURE_METHOD_PLAINTEXT = 'PLAINTEXT';
/**
* @var boolean
*/
protected $connect;
/**
* @var HttpUtils
*/
protected $httpUtils;
/**
* @var ResourceOwnerMap
*/
protected $ownerMap;
/**
* @var SecurityContextInterface
*
* @deprecated since 0.4. To be removed in 1.0. Use $authorizationChecker property instead.
*/
protected $securityContext;
/**
* SecurityContextInterface for Symfony <2.6
* To be removed with all related logic (constructor, configs, extension)
*
* @var AuthorizationCheckerInterface|SecurityContextInterface
*/
protected $authorizationChecker;
/**
* @param HttpUtils $httpUtils
* @param AuthorizationCheckerInterface|SecurityContextInterface $authorizationChecker
* @param boolean $connect
*/
public function __construct(HttpUtils $httpUtils, $authorizationChecker, $connect)
{
if (!$authorizationChecker instanceof AuthorizationCheckerInterface && !$authorizationChecker instanceof SecurityContextInterface) {
throw new \InvalidArgumentException('Argument 2 should be an instance of Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface or Symfony\Component\Security\Core\SecurityContextInterface');
}
$this->httpUtils = $httpUtils;
$this->authorizationChecker = $authorizationChecker;
$this->securityContext = $this->authorizationChecker;
$this->connect = $connect;
}
/**
* @param ResourceOwnerMap $ownerMap
*/
public function setResourceOwnerMap(ResourceOwnerMap $ownerMap)
{
$this->ownerMap = $ownerMap;
}
/**
* @return array
*/
public function getResourceOwners()
{
$resourceOwners = $this->ownerMap->getResourceOwners();
return array_keys($resourceOwners);
}
/**
* @param Request $request
* @param string $name
* @param string $redirectUrl Optional
* @param array $extraParameters Optional
*
* @return string
*/
public function getAuthorizationUrl(Request $request, $name, $redirectUrl = null, array $extraParameters = array())
{
$resourceOwner = $this->getResourceOwner($name);
if (null === $redirectUrl) {
if (!$this->connect || !$this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$redirectUrl = $this->httpUtils->generateUri($request, $this->ownerMap->getResourceOwnerCheckPath($name));
} else {
$redirectUrl = $this->getServiceAuthUrl($request, $resourceOwner);
}
}
return $resourceOwner->getAuthorizationUrl($redirectUrl, $extraParameters);
}
/**
* @param Request $request
* @param ResourceOwnerInterface $resourceOwner
*
* @return string
*/
public function getServiceAuthUrl(Request $request, ResourceOwnerInterface $resourceOwner)
{
if ($resourceOwner->getOption('auth_with_one_url')) {
$redirectUrl = $this->httpUtils->generateUri($request, $this->ownerMap->getResourceOwnerCheckPath($resourceOwner->getName())).'?authenticated=true';
} else {
$request->attributes->set('service', $resourceOwner->getName());
$redirectUrl = $this->httpUtils->generateUri($request, 'hwi_oauth_connect_service');
}
return $redirectUrl;
}
/**
* @param Request $request
* @param string $name
*
* @return string
*/
public function getLoginUrl(Request $request, $name)
{
// Just to check that this resource owner exists
$this->getResourceOwner($name);
$request->attributes->set('service', $name);
return $this->httpUtils->generateUri($request, 'hwi_oauth_service_redirect');
}
/**
* Sign the request parameters
*
* @param string $method Request method
* @param string $url Request url
* @param array $parameters Parameters for the request
* @param string $clientSecret Client secret to use as key part of signing
* @param string $tokenSecret Optional token secret to use with signing
* @param string $signatureMethod Optional signature method used to sign token
*
* @return string
*
* @throws \RuntimeException
*/
public static function signRequest($method, $url, $parameters, $clientSecret, $tokenSecret = '', $signatureMethod = self::SIGNATURE_METHOD_HMAC)
{
// Validate required parameters
foreach (array('oauth_consumer_key', 'oauth_timestamp', 'oauth_nonce', 'oauth_version', 'oauth_signature_method') as $parameter) {
if (!isset($parameters[$parameter])) {
throw new \RuntimeException(sprintf('Parameter "%s" must be set.', $parameter));
}
}
// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
if (isset($parameters['oauth_signature'])) {
unset($parameters['oauth_signature']);
}
// Parse & add query params as base string parameters if they exists
$url = parse_url($url);
if (isset($url['query'])) {
parse_str($url['query'], $queryParams);
$parameters += $queryParams;
}
// Remove default ports
// Ref: Spec: 9.1.2
$explicitPort = isset($url['port']) ? $url['port'] : null;
if (('https' === $url['scheme'] && 443 === $explicitPort) || ('http' === $url['scheme'] && 80 === $explicitPort)) {
$explicitPort = null;
}
// Remove query params from URL
// Ref: Spec: 9.1.2
$url = sprintf('%s://%s%s%s', $url['scheme'], $url['host'], ($explicitPort ? ':'.$explicitPort : ''), isset($url['path']) ? $url['path'] : '');
// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($parameters, 'strcmp');
// http_build_query should use RFC3986
$parts = array(
// HTTP method name must be uppercase
// Ref: Spec: 9.1.3 (1)
strtoupper($method),
rawurlencode($url),
rawurlencode(str_replace(array('%7E', '+'), array('~', '%20'), http_build_query($parameters, '', '&'))),
);
$baseString = implode('&', $parts);
switch ($signatureMethod) {
case self::SIGNATURE_METHOD_HMAC:
$keyParts = array(
rawurlencode($clientSecret),
rawurlencode($tokenSecret),
);
$signature = hash_hmac('sha1', $baseString, implode('&', $keyParts), true);
break;
case self::SIGNATURE_METHOD_RSA:
if (!function_exists('openssl_pkey_get_private')) {
throw new \RuntimeException('RSA-SHA1 signature method requires the OpenSSL extension.');
}
$privateKey = openssl_pkey_get_private(file_get_contents($clientSecret), $tokenSecret);
$signature = false;
openssl_sign($baseString, $signature, $privateKey);
openssl_free_key($privateKey);
break;
case self::SIGNATURE_METHOD_PLAINTEXT:
$signature = $baseString;
break;
default:
throw new \RuntimeException(sprintf('Unknown signature method selected %s.', $signatureMethod));
}
return base64_encode($signature);
}
/**
* @param string $name
*
* @return ResourceOwnerInterface
*
* @throws \RuntimeException
*/
protected function getResourceOwner($name)
{
$resourceOwner = $this->ownerMap->getResourceOwnerByName($name);
if (!$resourceOwner instanceof ResourceOwnerInterface) {
throw new \RuntimeException(sprintf("No resource owner with name '%s'.", $name));
}
return $resourceOwner;
}
}