summaryrefslogtreecommitdiff
path: root/src/products/app/Http/Middleware/Auth0Middleware.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/products/app/Http/Middleware/Auth0Middleware.php')
-rw-r--r--src/products/app/Http/Middleware/Auth0Middleware.php51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/products/app/Http/Middleware/Auth0Middleware.php b/src/products/app/Http/Middleware/Auth0Middleware.php
new file mode 100644
index 0000000..d4b5ebc
--- /dev/null
+++ b/src/products/app/Http/Middleware/Auth0Middleware.php
@@ -0,0 +1,51 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Auth0\SDK\Exception\InvalidTokenException;
+use Auth0\SDK\Helpers\JWKFetcher;
+use Auth0\SDK\Helpers\Tokens\AsymmetricVerifier;
+use Auth0\SDK\Helpers\Tokens\TokenVerifier;
+
+class Auth0Middleware
+{
+ public function handle($request, Closure $next, $scopeRequired = null)
+ {
+ $token = $request->bearerToken();
+
+ if (!$token)
+ return response()->json('No token provided', 401);
+
+ $decodedToken = $this->validateAndDecode($token);
+
+ if ($scopeRequired && !$this->tokenHasScope($decodedToken, $scopeRequired))
+ return response()->json(['message' => 'Missing permission'], 403);
+
+ return $next($request);
+ }
+
+ public function validateAndDecode($token)
+ {
+ try {
+ $jwksUri = env('AUTH0_DOMAIN') . '.well-known/jwks.json';
+ $jwksFetcher = new JWKFetcher(null, ['base_uri' => $jwksUri]);
+ $signatureVerifier = new AsymmetricVerifier($jwksFetcher);
+ $tokenVerifier = new TokenVerifier(env('AUTH0_DOMAIN'), env('AUTH0_AUD'), $signatureVerifier);
+
+ return $tokenVerifier->verify($token);
+ } catch (InvalidTokenException $e) {
+ throw $e;
+ }
+ }
+
+ protected function tokenHasScope($token, $scopeRequired)
+ {
+ if (empty($token['scope']))
+ return false;
+
+ $tokenScopes = explode(' ', $token['scope']);
+
+ return in_array($scopeRequired, $tokenScopes);
+ }
+}