-
Notifications
You must be signed in to change notification settings - Fork 48
/
Provider.php
286 lines (242 loc) · 7.95 KB
/
Provider.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
276
277
278
279
280
281
282
283
284
285
286
<?php
namespace SocialiteProviders\Apple;
use Firebase\JWT\JWK;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Laravel\Socialite\Two\InvalidStateException;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Psr\Http\Message\ResponseInterface;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;
class Provider extends AbstractProvider
{
public const IDENTIFIER = 'APPLE';
private const URL = 'https://appleid.apple.com';
protected $scopes = [
'name',
'email',
];
/**
* {@inheritdoc}
*/
protected $encodingType = PHP_QUERY_RFC3986;
protected $scopeSeparator = ' ';
protected function getAuthUrl($state): string
{
return $this->buildAuthUrlFromBase(self::URL.'/auth/authorize', $state);
}
protected function getTokenUrl(): string
{
return self::URL.'/auth/token';
}
/**
* {@inheritdoc}
*/
protected function getCodeFields($state = null)
{
$fields = [
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUrl,
'scope' => $this->formatScopes($this->getScopes(), $this->scopeSeparator),
'response_type' => 'code',
'response_mode' => 'form_post',
];
if ($this->usesState()) {
$fields['state'] = $state;
$fields['nonce'] = Str::uuid().'.'.$state;
}
return array_merge($fields, $this->parameters);
}
/**
* {@inheritdoc}
*/
public function getAccessTokenResponse($code)
{
$response = $this->getHttpClient()->post($this->getTokenUrl(), [
RequestOptions::HEADERS => ['Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret)],
RequestOptions::FORM_PARAMS => $this->getTokenFields($code),
]);
return json_decode((string) $response->getBody(), true);
}
/**
* {@inheritdoc}
*/
protected function getUserByToken($token)
{
static::verify($token);
$claims = explode('.', $token)[1];
return json_decode(base64_decode($claims), true);
}
/**
* Return the user given the identity token provided on the client
* side by Apple.
*
* @param string $token
* @return User $user
*
* @throws InvalidStateException when token can't be parsed
*/
public function userByIdentityToken(string $token): User
{
$array = $this->getUserByToken($token);
return $this->mapUserToObject($array);
}
/**
* Verify Apple jwt.
*
* @param string $jwt
* @return bool
*
* @see https://appleid.apple.com/auth/keys
*/
public static function verify($jwt)
{
$jwtContainer = Configuration::forSymmetricSigner(
new AppleSignerNone,
AppleSignerInMemory::plainText('')
);
$token = $jwtContainer->parser()->parse($jwt);
$data = Cache::remember('socialite:Apple-JWKSet', 5 * 60, function () {
$response = (new Client)->get(self::URL.'/auth/keys');
return json_decode((string) $response->getBody(), true);
});
$publicKeys = JWK::parseKeySet($data);
$kid = $token->headers()->get('kid');
if (isset($publicKeys[$kid])) {
$publicKey = openssl_pkey_get_details($publicKeys[$kid]->getKeyMaterial());
$constraints = [
new SignedWith(new Sha256, AppleSignerInMemory::plainText($publicKey['key'])),
new IssuedBy(self::URL),
new LooseValidAt(SystemClock::fromSystemTimezone()),
];
try {
$jwtContainer->validator()->assert($token, ...$constraints);
return true;
} catch (RequiredConstraintsViolated $e) {
throw new InvalidStateException($e->getMessage());
}
}
throw new InvalidStateException('Invalid JWT Signature');
}
/**
* {@inheritdoc}
*/
public function user()
{
//Temporary fix to enable stateless
$response = $this->getAccessTokenResponse($this->getCode());
$appleUserToken = $this->getUserByToken(
$token = Arr::get($response, 'id_token')
);
if ($this->usesState()) {
$state = explode('.', $appleUserToken['nonce'])[1];
if ($state === $this->request->input('state')) {
$this->request->session()->put([
'state' => $state,
'state_verify' => $state,
]);
}
if ($this->hasInvalidState()) {
throw new InvalidStateException;
}
}
$user = $this->mapUserToObject($appleUserToken);
if ($user instanceof User) {
$user->setAccessTokenResponseBody($response);
}
return $user->setToken($token)
->setRefreshToken(Arr::get($response, 'refresh_token'))
->setExpiresIn(Arr::get($response, 'expires_in'));
}
/**
* {@inheritdoc}
*/
protected function mapUserToObject(array $user)
{
$userRequest = $this->getUserRequest();
if (isset($userRequest['name'])) {
$user['name'] = $userRequest['name'];
$fullName = trim(
($user['name']['firstName'] ?? '')
.' '
.($user['name']['lastName'] ?? '')
);
}
return (new User)
->setRaw($user)
->map([
'id' => $user['sub'],
'name' => $fullName ?? null,
'email' => $user['email'] ?? null,
]);
}
private function getUserRequest(): array
{
$value = $this->request->input('user');
if (is_array($value)) {
return $value;
}
$value = trim((string) $value);
if ($value === '') {
return [];
}
return json_decode($value, true);
}
/**
* @return string
*/
protected function getRevokeUrl(): string
{
return self::URL.'/auth/revoke';
}
/**
* @param string $token
* @param string $hint
* @return \Psr\Http\Message\ResponseInterface
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function revokeToken(string $token, string $hint = 'access_token')
{
return $this->getHttpClient()->post($this->getRevokeUrl(), [
RequestOptions::FORM_PARAMS => [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'token' => $token,
'token_type_hint' => $hint,
],
]);
}
/**
* Acquire a new access token using the refresh token.
*
* Refer to the documentation for the response structure (the `refresh_token` will be missing from the new response).
*
* @see https://developer.apple.com/documentation/sign_in_with_apple/tokenresponse
*
* @param string $refreshToken
* @return ResponseInterface
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function refreshToken($refreshToken): ResponseInterface
{
return $this->getHttpClient()->post($this->getTokenUrl(), [
RequestOptions::FORM_PARAMS => [
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
],
]);
}
}