1: <?php
2:
3: namespace LaravelUi5\Core\Middleware;
4:
5: use Closure;
6: use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
7: use Illuminate\Http\Exceptions\HttpResponseException;
8:
9: class VerifyCsrfToken extends ValidateCsrfToken
10: {
11: /**
12: * From SAP documentation:
13: *
14: * > If a data request fails with status 403 and an "X-CSRF-Token" response header value "required" (case insensitive),
15: * a new security token will be fetched and the data request will be repeated automatically and transparently.
16: * >
17: * > A new security token is fetched via a HEAD request on the service URL using an "X-CSRF-Token" header value "Fetch".
18: * The response header value of "X-CSRF-Token" is remembered if present, or else that header will not be used any longer.
19: *
20: * @see https://sapui5.hana.ondemand.com/sdk/#/topic/9613f1f2d88747cab21896f7216afdac.html
21: * @see FetchCsrfToken
22: *
23: * @param $request
24: * @param Closure $next
25: * @return \Illuminate\Support\HigherOrderTapProxy|mixed
26: */
27: public function handle($request, Closure $next): mixed
28: {
29: if (
30: $this->isReading($request) ||
31: $this->runningUnitTests() ||
32: $this->inExceptArray($request) ||
33: $this->tokensMatch($request)
34: ) {
35: return tap($next($request), function ($response) use ($request) {
36: if ($this->shouldAddXsrfTokenCookie()) {
37: $this->addCookieToResponse($request, $response);
38: }
39: });
40: }
41:
42: throw new HttpResponseException(
43: response('CSRF token mismatch.')
44: ->header('X-CSRF-Token', 'required')
45: ->setStatusCode(403)
46: );
47: }
48: }
49: