Skip to content

Commit 54f8698

Browse files
committed
Cache by user->sub, update to auth0 8
1 parent 3c3d3dd commit 54f8698

File tree

3 files changed

+34
-89
lines changed

3 files changed

+34
-89
lines changed

config/config.php

-4
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,4 @@
1313

1414
// The base URL for the user service
1515
'user_api_base_url' => env('AUTH0_USER_API'),
16-
17-
// The URI for the JWKS file (fallback to https://gsv.eu.auth0.com/.well-known/jwks.json)
18-
'jwks_uri' => null,
19-
2016
];

src/GsvAuth0Provider.php

+33-68
Original file line numberDiff line numberDiff line change
@@ -9,57 +9,44 @@
99
use Illuminate\Support\Carbon;
1010
use Illuminate\Support\Facades\Gate;
1111
use Illuminate\Support\Str;
12+
use Illuminate\Support\Facades\Cache;
13+
14+
use Auth0\SDK\Token;
15+
use Auth0\SDK\Configuration\SdkConfiguration;
1216

1317
class GsvAuth0Provider
1418
{
15-
protected $auth0_domain;
16-
17-
protected $api_identifier;
18-
19-
protected $jwks_uri;
19+
protected $configuration;
2020

21-
protected $cache;
22-
23-
public function __construct(?string $auth0_domain, ?string $api_identifier, ?string $jwks_uri = null)
21+
public function __construct(?string $domain, ?string $audience)
2422
{
25-
$this->auth0_domain = $auth0_domain;
26-
$this->api_identifier = $api_identifier;
27-
28-
$this->jwks_uri = $jwks_uri ?: sprintf('https://%s/.well-known/jwks.json', $this->auth0_domain);
29-
30-
$this->cache = app()->make('cache.store');
31-
32-
// Add a neat little custom method that only caches if a condition is met
33-
$this->cache->macro('rememberWhen', function ($condition, $key, $ttl, $callback) {
34-
if ($condition) {
35-
return $this->remember($key, $ttl, $callback);
36-
} else {
37-
return $callback();
38-
}
39-
});
23+
$this->configuration = new SdkConfiguration(
24+
domain: $domain,
25+
audience: [$audience],
26+
clientId: 'dummy', // Don't need a real value as we only validate jwt's
27+
clientSecret: 'dummy', // Don't need a real value as we only validate jwt's
28+
cookieSecret: 'dummy', // Don't need a real value as we only validate jwt's
29+
);
4030
}
4131

4232
/**
43-
* Authenticate the token
33+
* Authenticate the jwt
4434
*
4535
* @param string $token
4636
* @return self
4737
*/
48-
public function authenticate(string $token): self
38+
public function authenticate(string $jwt): self
4939
{
50-
if ($this->auth0_domain === null) {
51-
throw new Exception('Auth0 domain not set');
52-
}
53-
54-
if ($this->api_identifier === null) {
55-
throw new Exception('API identifier not set');
40+
if ($this->configuration === null) {
41+
throw new Exception('Auth0 configuration not set');
5642
}
5743

5844
try {
59-
$info = $this->decodeJWT($token);
60-
61-
$this->setUser($info, $token);
62-
} catch (InvalidTokenException $e) {
45+
$token = new Token($this->configuration, $jwt, \Auth0\SDK\Token::TYPE_ACCESS_TOKEN);
46+
$token->verify();
47+
$token->validate();
48+
$this->setUser($token->toArray(), $jwt);
49+
} catch (\Exception $e) {
6350
// Re-throw into a 401
6451
throw new InvalidTokenException($e->getMessage(), 401);
6552
}
@@ -78,14 +65,17 @@ public function loadUserData(Auth0User $user = null): self
7865

7966
$client = app()->make('gsv-auth0-user-service');
8067

81-
$userData = $this->cache->rememberWhen(
82-
$user->expires->isAfter(Carbon::now()), // Only cache if this condition is met
83-
md5($user->token), // The cache key
84-
$user->expires->diffInSeconds(Carbon::now()), // Cache expires when the auth expires
85-
function () use ($client, $user) {
86-
return $client->setToken($user->token)->fetch($user->auth0_id);
87-
}
88-
);
68+
if ($user->expires->isAfter(Carbon::now())) {
69+
$userData = Cache::remember(
70+
md5($user->sub),
71+
$user->expires->diffInSeconds(Carbon::now()),
72+
function () use ($client, $user) {
73+
return $client->setToken($user->token)->fetch($user->auth0_id);
74+
}
75+
);
76+
} else {
77+
$userData = $client->setToken($user->token)->fetch($user->auth0_id);
78+
}
8979

9080
if ((isset($userData['status']) && $userData['status'] === 'Error') || empty($userData['data'])) {
9181
throw new UserNotFoundException($userData['message'], 401);
@@ -158,29 +148,4 @@ protected function setUser(array $info, string $token): self
158148

159149
return $this;
160150
}
161-
162-
/**
163-
* Verify a JWT from Auth0
164-
*
165-
* @see https://github.com/auth0/laravel-auth0/blob/8377bd09644de60d5a8688653589ea299ccd2969/src/Auth0/Login/Auth0Service.php#L206
166-
* @param string $encUser
167-
* @param array $verifierOptions
168-
* @throws InvalidTokenException
169-
* @return array
170-
*/
171-
protected function decodeJWT(string $encUser, array $verifierOptions = []): array
172-
{
173-
$jwks_fetcher = app()->make('gsv-auth0-jwks-fetcher', [
174-
'cache' => $this->cache,
175-
]);
176-
$jwks = $jwks_fetcher->getKeys($this->jwks_uri);
177-
178-
$token_verifier = app()->make('gsv-auth0-token-verifier', [
179-
'domain' => $this->auth0_domain,
180-
'apiIdentifier' => $this->api_identifier,
181-
'jwks' => $jwks,
182-
]);
183-
184-
return $token_verifier->verify($encUser, $verifierOptions);
185-
}
186151
}

src/GsvAuth0ProviderServiceProvider.php

+1-17
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22

33
namespace Adaptdk\GsvAuth0Provider;
44

5-
use Auth0\SDK\Helpers\JWKFetcher;
6-
use Auth0\SDK\Helpers\Tokens\AsymmetricVerifier;
7-
use Auth0\SDK\Helpers\Tokens\TokenVerifier;
85
use Illuminate\Http\Request;
96
use Illuminate\Support\Facades\Auth;
107
use Illuminate\Support\ServiceProvider;
@@ -29,8 +26,7 @@ public function register()
2926
$this->app->singleton('gsv-auth0-provider', function () {
3027
return new GsvAuth0Provider(
3128
config('gsv-auth0-provider.domain'),
32-
config('gsv-auth0-provider.api_identifier'),
33-
config('gsv-auth0-provider.jwks_uri')
29+
config('gsv-auth0-provider.api_identifier')
3430
);
3531
});
3632

@@ -39,18 +35,6 @@ public function register()
3935
return new UserService(config('gsv-auth0-provider.user_api_base_url'));
4036
});
4137

42-
$this->app->bind('gsv-auth0-jwks-fetcher', function ($app, $params) {
43-
return new JWKFetcher($params['cache']);
44-
});
45-
46-
$this->app->bind('gsv-auth0-token-verifier', function ($app, $params) {
47-
return new TokenVerifier(
48-
sprintf('https://%s/', $params['domain']),
49-
$params['apiIdentifier'],
50-
new AsymmetricVerifier($params['jwks']),
51-
);
52-
});
53-
5438
// Open the gates
5539
Auth::viaRequest('gsv-auth0-provider', function (Request $request) {
5640
$token = $request->bearerToken() ?: $request->query('authToken');

0 commit comments

Comments
 (0)