forked from yiisoft/yii2-authclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OAuth2.php
272 lines (236 loc) · 8.06 KB
/
OAuth2.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
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\authclient;
use Yii;
use yii\web\HttpException;
/**
* OAuth2 serves as a client for the OAuth 2 flow.
*
* In oder to acquire access token perform following sequence:
*
* ```php
* use yii\authclient\OAuth2;
*
* $oauthClient = new OAuth2();
* $url = $oauthClient->buildAuthUrl(); // Build authorization URL
* Yii::$app->getResponse()->redirect($url); // Redirect to authorization URL.
* // After user returns at our site:
* $code = $_GET['code'];
* $accessToken = $oauthClient->fetchAccessToken($code); // Get access token
* ```
*
* @see http://oauth.net/2/
* @see https://tools.ietf.org/html/rfc6749
*
* @author Paul Klimov <[email protected]>
* @since 2.0
*/
abstract class OAuth2 extends BaseOAuth
{
/**
* @var string protocol version.
*/
public $version = '2.0';
/**
* @var string OAuth client ID.
*/
public $clientId;
/**
* @var string OAuth client secret.
*/
public $clientSecret;
/**
* @var string token request URL endpoint.
*/
public $tokenUrl;
/**
* @var boolean whether to use and validate auth 'state' parameter in authentication flow.
* If enabled - the opaque value will be generated and applied to auth URL to maintain
* state between the request and callback. The authorization server includes this value,
* when redirecting the user-agent back to the client.
* The option is used for preventing cross-site request forgery.
* @since 2.1
*/
public $validateAuthState = true;
/**
* Composes user authorization URL.
* @param array $params additional auth GET params.
* @return string authorization URL.
*/
public function buildAuthUrl(array $params = [])
{
$defaultParams = [
'client_id' => $this->clientId,
'response_type' => 'code',
'redirect_uri' => $this->getReturnUrl(),
'xoauth_displayname' => Yii::$app->name,
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
if ($this->validateAuthState) {
$authState = $this->generateAuthState();
$this->setState('authState', $authState);
$defaultParams['state'] = $authState;
}
return $this->composeUrl($this->authUrl, array_merge($defaultParams, $params));
}
/**
* Fetches access token from authorization code.
* @param string $authCode authorization code, usually comes at $_GET['code'].
* @param array $params additional request params.
* @return OAuthToken access token.
* @throws HttpException on invalid auth state in case [[enableStateValidation]] is enabled.
*/
public function fetchAccessToken($authCode, array $params = [])
{
if ($this->validateAuthState) {
$authState = $this->getState('authState');
if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) {
throw new HttpException(400, 'Invalid auth state parameter.');
} else {
$this->removeState('authState');
}
}
$defaultParams = [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'code' => $authCode,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->getReturnUrl(),
];
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
/**
* @inheritdoc
*/
public function applyAccessTokenToRequest($request, $accessToken)
{
$data = $request->getData();
$data['access_token'] = $accessToken->getToken();
$request->setData($data);
}
/**
* Gets new auth token to replace expired one.
* @param OAuthToken $token expired auth token.
* @return OAuthToken new auth token.
*/
public function refreshAccessToken(OAuthToken $token)
{
$params = [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'refresh_token'
];
$params = array_merge($token->getParams(), $params);
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData($params);
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
/**
* Composes default [[returnUrl]] value.
* @return string return URL.
*/
protected function defaultReturnUrl()
{
$params = $_GET;
unset($params['code']);
unset($params['state']);
$params[0] = Yii::$app->controller->getRoute();
return Yii::$app->getUrlManager()->createAbsoluteUrl($params);
}
/**
* Generates the auth state value.
* @return string auth state value.
* @since 2.1
*/
protected function generateAuthState()
{
$baseString = get_class($this) . '-' . time();
if (Yii::$app->has('session')) {
$baseString .= '-' . Yii::$app->session->getId();
}
return hash('sha256', uniqid($baseString, true));
}
/**
* Creates token from its configuration.
* @param array $tokenConfig token configuration.
* @return OAuthToken token instance.
*/
protected function createToken(array $tokenConfig = [])
{
$tokenConfig['tokenParamKey'] = 'access_token';
return parent::createToken($tokenConfig);
}
/**
* Authenticate OAuth client directly at the provider without third party (user) involved,
* using 'client_credentials' grant type.
* @see http://tools.ietf.org/html/rfc6749#section-4.4
* @param array $params additional request params.
* @return OAuthToken access token.
*/
public function authenticateClient($params = [])
{
$defaultParams = [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'client_credentials',
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
/**
* Authenticates user directly by 'username/password' pair, using 'password' grant type.
* @see https://tools.ietf.org/html/rfc6749#section-4.3
* @param string $username user name.
* @param string $password user password.
* @param array $params additional request params.
* @return OAuthToken access token.
*/
public function authenticateUser($username, $password, $params = [])
{
$defaultParams = [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'password',
'username' => $username,
'password' => $password,
];
if (!empty($this->scope)) {
$defaultParams['scope'] = $this->scope;
}
$request = $this->createRequest()
->setMethod('POST')
->setUrl($this->tokenUrl)
->setData(array_merge($defaultParams, $params));
$response = $this->sendRequest($request);
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
}