-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAuthCodeController.php
196 lines (166 loc) · 5.73 KB
/
AuthCodeController.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
<?php
namespace NPR\One\Controllers;
use NPR\One\DI\DI;
use NPR\One\Interfaces\{ConfigInterface, StorageInterface};
use NPR\One\Models\AccessTokenModel;
use NPR\One\Providers\CookieProvider;
/**
* Use this controller to power your OAuth2 proxy if you are using the `authorization_code` grant.
* The consumer of this codebase is responsible for setting up a router which forwards on the relevant requests
* to the {@see AuthCodeController::startAuthorizationGrant()} and {@see AuthCodeController::completeAuthorizationGrant()}
* public methods in this class.
*
* @package NPR\One\Controllers
*/
class AuthCodeController extends AbstractOAuth2Controller
{
/** @internal */
const ONE_DAY = 86400; // in seconds
/** @var StorageInterface
* @internal */
private $storage;
/** @var CookieProvider
* @internal */
private $cookies;
/**
* {@inheritdoc}
*/
public function __construct()
{
parent::__construct();
$this->cookies = DI::container()->get(CookieProvider::class);
}
/**
* {@inheritdoc}
*/
public function setConfigProvider(ConfigInterface $configProvider): AbstractOAuth2Controller
{
parent::setConfigProvider($configProvider);
$this->cookies->setDomain($configProvider->getCookieDomain());
$this->cookies->setKeyPrefix($configProvider->getCookiePrefix());
return $this;
}
/**
* Sets a storage provider to use across PHP sessions. Used to validate the OAuth `state` param.
*
* @param StorageInterface $storageProvider
* @return $this
*/
public function setStorageProvider(StorageInterface $storageProvider): AuthCodeController
{
$this->storage = $storageProvider;
return $this;
}
/**
* {@inheritdoc}
* @internal
*/
final protected function ensureExternalProvidersExist()
{
parent::ensureExternalProvidersExist();
if (empty($this->storage))
{
throw new \RuntimeException('StorageProvider must be set. See ' . __CLASS__ . '::setStorageProvider.');
}
}
/**
* Returns the webapp URL as set in the configuration provider.
*
* @return string
*/
public function getRedirectUri(): string
{
$this->ensureExternalProvidersExist();
return $this->getConfigProvider()->getClientUrl();
}
/**
* Kicks off a new authorization grant flow
*
* @api
* @param string[] $scopes
* @return string
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function startAuthorizationGrant(array $scopes): string
{
$this->ensureExternalProvidersExist();
$this->validateScopes($scopes);
$queryParams = [
'client_id' => $this->getConfigProvider()->getClientId(),
'redirect_uri' => $this->getConfigProvider()->getAuthCodeCallbackUrl(),
'state' => $this->generateOAuth2State(),
'response_type' => 'code',
'prompt' => 'login',
'scope' => join(' ', $scopes)
];
return $this->getConfigProvider()->getNprAuthorizationServiceHost() . '/v2/authorize?' . http_build_query($queryParams);
}
/**
* Finishes the authorization grant flow
*
* @api
* @param string $authorizationCode
* @param string $state
* @return AccessTokenModel - useful for debugging
* @throws \InvalidArgumentException
* @throws \Exception when state param is invalid
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function completeAuthorizationGrant($authorizationCode, $state): AccessTokenModel
{
if (empty($authorizationCode) || !is_string($authorizationCode))
{
throw new \InvalidArgumentException('Must specify authorization code');
}
if (empty($state) || !is_string($state))
{
throw new \InvalidArgumentException('Must specify state');
}
$this->ensureExternalProvidersExist();
$this->verifyOAuth2State($state);
$accessToken = $this->createAccessToken('authorization_code', [
'code' => $authorizationCode,
'redirect_uri' => $this->getConfigProvider()->getAuthCodeCallbackUrl()
]);
$this->cookies->set('access_token', $accessToken->getAccessToken(), $accessToken->getExpiresIn());
$this->storeRefreshToken($accessToken);
return $accessToken;
}
/**
* Generates a new state string comprised of a key and a value. Session storage is
* required to persist the key & value across the redirect requests.
*
* @internal
* @return string
*/
private function generateOAuth2State(): string
{
$key = mt_rand();
$value = mt_rand();
$this->storage->set($key, $value, self::ONE_DAY);
return $key . ':' . $value;
}
/**
* Checks sessions storage to ensure that the state value is the correct value given earlier
* in the flow
*
* @internal
* @param string $serverState
* @throws \Exception when state is invalid
*/
private function verifyOAuth2State($serverState)
{
if (strpos($serverState, ':') === false)
{
throw new \Exception("Invalid state returned from OAuth server, colon separator missing: $serverState");
}
list($serverKey, $serverValue) = explode(':', $serverState);
$compareResult = $this->storage->compare($serverKey, $serverValue);
$this->storage->remove($serverKey);
if (!$compareResult)
{
throw new \Exception("Invalid state returned from OAuth server, server state '$serverState' does not match stored value");
}
}
}