From ce6c0cf4003b3676488e2911383282fce42957fe Mon Sep 17 00:00:00 2001 From: utilewebsites <31533865+utilewebsites@users.noreply.github.com> Date: Thu, 12 Sep 2024 14:34:02 +0200 Subject: [PATCH] Fix origin denied issue by trimming trailing slash from APP_URL and HTTP_ORIGIN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue Description: When using the current version of the TinymceMiddleware in the Murdercode/Nova4-TinymceEditor package, the origin verification logic does not handle minor discrepancies such as a trailing slash in the URL, causing valid CORS requests to be rejected with a 403 Origin Denied error. This issue arises because the APP_URL defined in the .env file may contain a trailing slash, while the HTTP_ORIGIN header from the request typically does not. Proposed Solution: To resolve this issue, the proposed changes trim the trailing slash from both APP_URL and the HTTP_ORIGIN header before performing the origin validation. This ensures that even if there is a slight mismatch in the format of the URLs (with or without a trailing slash), valid requests will still pass the CORS check. Code Changes: In the TinymceMiddleware class: Before: The code directly compares config('app.url') with $_SERVER['HTTP_ORIGIN'], which caused mismatches if one contained a trailing slash. After: Both config('app.url') and $_SERVER['HTTP_ORIGIN'] are trimmed of their trailing slashes using rtrim(), ensuring consistent comparison and preventing unnecessary "Origin denied" errors. Benefits: This change resolves the issue of CORS requests being denied due to inconsistent URL formatting, especially when using APP_URL with a trailing slash in the .env file. The solution enhances the middleware’s robustness and avoids common pitfalls that could frustrate developers using the package in different environments. --- src/Http/Middleware/TinymceMiddleware.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Http/Middleware/TinymceMiddleware.php b/src/Http/Middleware/TinymceMiddleware.php index b224bb7..d3690df 100644 --- a/src/Http/Middleware/TinymceMiddleware.php +++ b/src/Http/Middleware/TinymceMiddleware.php @@ -22,17 +22,19 @@ public function handle($request, Closure $next) /** * Check if the request coming from the same origin */ - $accepted_origins = [config('app.url')]; - if (isset($_SERVER['HTTP_ORIGIN'])) { - if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { - header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); + $accepted_origins = [rtrim(config('app.url'), '/')]; + $origin = rtrim($_SERVER['HTTP_ORIGIN'], '/'); + + if (isset($origin)) { + if (in_array($origin, $accepted_origins)) { + header('Access-Control-Allow-Origin: ' . $origin); } else { header('HTTP/1.1 403 Origin Denied'); - return response()->json(['error' => 'Origin denied']); } } + return $next($request); } }