summaryrefslogtreecommitdiff
path: root/src/products/app/Http/Middleware/Auth0Middleware.php
blob: d4b5ebc77015b4796d3db1959180e87d7c70beff (plain) (blame)
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
<?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);
	}
}