| 1: | <?php |
| 2: | |
| 3: | namespace LaravelUi5\Core\Middleware; |
| 4: | |
| 5: | use Closure; |
| 6: | use Illuminate\Http\Request; |
| 7: | |
| 8: | /** |
| 9: | * From SAP documentation: **Security Token Handling** |
| 10: | * |
| 11: | * > The OData V4 model automatically handles a security token via an "X-CSRF-Token" |
| 12: | * header if needed by its service. To achieve this, the "X-CSRF-Token" header starts |
| 13: | * with a value of "Fetch" and will be included in every data request. If a data |
| 14: | * response contains the "X-CSRF-Token" header, that new value will be remembered |
| 15: | * and used from that time on. |
| 16: | * |
| 17: | * This middleware ensures that when a request asks for a CSRF token |
| 18: | * (`X-CSRF-Token: Fetch`), the response will include the current CSRF token |
| 19: | * in the `X-CSRF-Token` header. |
| 20: | * |
| 21: | * @see https://sapui5.hana.ondemand.com/sdk/#/topic/9613f1f2d88747cab21896f7216afdac.html |
| 22: | * @see VerifyCsrfToken |
| 23: | */ |
| 24: | class FetchCsrfToken |
| 25: | { |
| 26: | /** |
| 27: | * Handle an incoming request. |
| 28: | * |
| 29: | * @param Request $request |
| 30: | * @param Closure $next |
| 31: | * @return mixed |
| 32: | */ |
| 33: | public function handle(Request $request, Closure $next): mixed |
| 34: | { |
| 35: | $response = $next($request); |
| 36: | |
| 37: | if ('Fetch' === $request->header('X-CSRF-Token')) { |
| 38: | $token = csrf_token(); |
| 39: | |
| 40: | $response->headers->set('X-CSRF-Token', $token); |
| 41: | } |
| 42: | |
| 43: | return $response; |
| 44: | } |
| 45: | } |
| 46: |