-
Notifications
You must be signed in to change notification settings - Fork 785
/
Copy pathTokenGuard.php
288 lines (256 loc) · 8.88 KB
/
TokenGuard.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
287
288
<?php
namespace Laravel\Passport\Guards;
use Exception;
use Firebase\JWT\JWT;
use Illuminate\Container\Container;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Http\Request;
use Laravel\Passport\ClientRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\TokenRepository;
use Laravel\Passport\TransientToken;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\ResourceServer;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
class TokenGuard
{
/**
* The resource server instance.
*
* @var \League\OAuth2\Server\ResourceServer
*/
protected $server;
/**
* The user provider implementation.
*
* @var \Illuminate\Contracts\Auth\UserProvider
*/
protected $provider;
/**
* The token repository instance.
*
* @var \Laravel\Passport\TokenRepository
*/
protected $tokens;
/**
* The client repository instance.
*
* @var \Laravel\Passport\ClientRepository
*/
protected $clients;
/**
* The encrypter implementation.
*
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
protected $encrypter;
/**
* Create a new token guard instance.
*
* @param \League\OAuth2\Server\ResourceServer $server
* @param \Illuminate\Contracts\Auth\UserProvider $provider
* @param \Laravel\Passport\TokenRepository $tokens
* @param \Laravel\Passport\ClientRepository $clients
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @return void
*/
public function __construct(ResourceServer $server,
UserProvider $provider,
TokenRepository $tokens,
ClientRepository $clients,
Encrypter $encrypter)
{
$this->server = $server;
$this->tokens = $tokens;
$this->clients = $clients;
$this->provider = $provider;
$this->encrypter = $encrypter;
}
/**
* Get the user for the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function user(Request $request)
{
if ($request->bearerToken()) {
return $this->authenticateViaBearerToken($request);
} elseif ($request->cookie(Passport::cookie())) {
return $this->authenticateViaCookie($request);
}
}
/**
* Get the client for the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function client(Request $request)
{
if ($request->bearerToken()) {
if (! $psr = $this->getPsrRequestViaBearerToken($request)) {
return;
}
return $this->clients->findActive(
$psr->getAttribute('oauth_client_id')
);
} elseif ($request->cookie(Passport::cookie())) {
if ($token = $this->getTokenViaCookie($request)) {
return $this->clients->findActive($token['aud']);
}
}
}
/**
* Authenticate the incoming request via the Bearer token.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
protected function authenticateViaBearerToken($request)
{
if (! $psr = $this->getPsrRequestViaBearerToken($request)) {
return;
}
// If the access token is valid we will retrieve the user according to the user ID
// associated with the token. We will use the provider implementation which may
// be used to retrieve users from Eloquent. Next, we'll be ready to continue.
$user = $this->provider->retrieveById(
$psr->getAttribute('oauth_user_id') ?: null
);
if (! $user) {
return;
}
// Next, we will assign a token instance to this user which the developers may use
// to determine if the token has a given scope, etc. This will be useful during
// authorization such as within the developer's Laravel model policy classes.
$token = $this->tokens->find(
$psr->getAttribute('oauth_access_token_id')
);
$clientId = $psr->getAttribute('oauth_client_id');
// Finally, we will verify if the client that issued this token is still valid and
// its tokens may still be used. If not, we will bail out since we don't want a
// user to be able to send access tokens for deleted or revoked applications.
if ($this->clients->revoked($clientId)) {
return;
}
return $token ? $user->withAccessToken($token) : null;
}
/**
* Authenticate and get the incoming PSR-7 request via the Bearer token.
*
* @param \Illuminate\Http\Request $request
* @return \Psr\Http\Message\ServerRequestInterface
*/
protected function getPsrRequestViaBearerToken($request)
{
// First, we will convert the Symfony request to a PSR-7 implementation which will
// be compatible with the base OAuth2 library. The Symfony bridge can perform a
// conversion for us to a Zend Diactoros implementation of the PSR-7 request.
$psr = (new DiactorosFactory)->createRequest($request);
try {
return $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
$request->headers->set('Authorization', '', true);
Container::getInstance()->make(
ExceptionHandler::class
)->report($e);
}
}
/**
* Authenticate the incoming request via the token cookie.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
protected function authenticateViaCookie($request)
{
if (! $token = $this->getTokenViaCookie($request)) {
return;
}
// If this user exists, we will return this user and attach a "transient" token to
// the user model. The transient token assumes it has all scopes since the user
// is physically logged into the application via the application's interface.
if ($user = $this->provider->retrieveById($token['sub'])) {
return $user->withAccessToken(new TransientToken);
}
}
/**
* Get the token cookie via the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
protected function getTokenViaCookie($request)
{
// If we need to retrieve the token from the cookie, it'll be encrypted so we must
// first decrypt the cookie and then attempt to find the token value within the
// database. If we can't decrypt the value we'll bail out with a null return.
try {
$token = $this->decodeJwtTokenCookie($request);
} catch (Exception $e) {
return;
}
// We will compare the CSRF token in the decoded API token against the CSRF header
// sent with the request. If they don't match then this request isn't sent from
// a valid source and we won't authenticate the request for further handling.
if (! Passport::$ignoreCsrfToken && (! $this->validCsrf($token, $request) ||
time() >= $token['expiry'])) {
return;
}
return $token;
}
/**
* Decode and decrypt the JWT token cookie.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function decodeJwtTokenCookie($request)
{
return (array) JWT::decode(
$this->encrypter->decrypt($request->cookie(Passport::cookie()), Passport::$unserializesCookies),
$this->encrypter->getKey(),
['HS256']
);
}
/**
* Determine if the CSRF / header are valid and match.
*
* @param array $token
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function validCsrf($token, $request)
{
return isset($token['csrf']) && hash_equals(
$token['csrf'], (string) $this->getTokenFromRequest($request)
);
}
/**
* Get the CSRF token from the request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getTokenFromRequest($request)
{
$token = $request->header('X-CSRF-TOKEN');
if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header, static::serialized());
}
return $token;
}
/**
* Determine if the cookie contents should be serialized.
*
* @return bool
*/
public static function serialized()
{
return EncryptCookies::serialized('XSRF-TOKEN');
}
}