Skip to content

A self-hosted media server and file management system

feat: custom xsrf cookie name

aminnausinc15f131aff4e
diff --git a/app/Http/Middleware/ValidateCsrfToken.php b/app/Http/Middleware/ValidateCsrfToken.php
new file mode 100644
index 00000000..ff8b746c
--- /dev/null
+++ b/app/Http/Middleware/ValidateCsrfToken.php
@@ -0,0 +1,99 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Contracts\Encryption\DecryptException;
+use Illuminate\Cookie\Middleware\EncryptCookies;
+use Illuminate\Cookie\CookieValuePrefix;
+use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
+use Illuminate\Session\TokenMismatchException;
+use Symfony\Component\HttpFoundation\Cookie;
+
+class ValidateCsrfToken extends VerifyCsrfToken {
+ /**
+ * The URIs that should be excluded.
+ *
+ * @var array<int, string>
+ */
+ protected $except = [];
+
+ /**
+ * Handle an incoming request.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @param \Closure $next
+ * @return mixed
+ *
+ * @throws \Illuminate\Session\TokenMismatchException
+ */
+ public function handle($request, Closure $next) {
+ if (
+ $this->isReading($request) ||
+ $this->runningUnitTests() ||
+ $this->inExceptArray($request) ||
+ $this->tokensMatch($request)
+ ) {
+ return tap($next($request), function ($response) use ($request) {
+ if ($this->shouldAddXsrfTokenCookie()) {
+ $this->addCookieToResponse($request, $response);
+ }
+ });
+ }
+
+ throw new TokenMismatchException('CSRF token mismatch.');
+ }
+
+ /**
+ * Get the CSRF token from the request.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @return string|null
+ */
+ protected function getTokenFromRequest($request) {
+ $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
+
+ if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
+ try {
+ $token = CookieValuePrefix::remove($this->encrypter->decrypt($header, static::serialized()));
+ } catch (DecryptException) {
+ $token = '';
+ }
+ }
+
+ return $token;
+ }
+
+ /**
+ * Create a new "{app.name}_XSRF-TOKEN" cookie that contains the CSRF token.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @param array $config
+ * @return \Symfony\Component\HttpFoundation\Cookie
+ */
+ protected function newCookie($request, $config) {
+ return new Cookie(
+ // 'XSRF-TOKEN',
+ config('app.name', 'MediaServer') . '_XSRF-TOKEN',
+ $request->session()->token(),
+ $this->availableAt(60 * $config['lifetime']),
+ $config['path'],
+ $config['domain'],
+ $config['secure'],
+ false,
+ false,
+ $config['same_site'] ?? null,
+ $config['partitioned'] ?? false
+ );
+ }
+
+ /**
+ * Determine if the cookie contents should be serialized.
+ *
+ * @return bool
+ */
+ public static function serialized() {
+ // return EncryptCookies::serialized('XSRF-TOKEN');
+ return EncryptCookies::serialized(config('app.name', 'MediaServer') . '_XSRF-TOKEN');
+ }
+}
diff --git a/bootstrap/app.php b/bootstrap/app.php
index cd15d87b..c5344c05 100755
--- a/bootstrap/app.php
+++ b/bootstrap/app.php
@@ -28,10 +28,15 @@ return Application::configure(basePath: dirname(__DIR__))
Request::HEADER_X_FORWARDED_AWS_ELB
);
$middleware->statefulApi();
- $middleware->trustHosts(at: fn () => config('app.trusted_hosts'));
- $middleware->web(append: [
- \App\Http\Middleware\UserLastActive::class,
- ]);
+ $middleware->trustHosts(at: fn() => config('app.trusted_hosts'));
+ $middleware->web(
+ replace: [
+ \Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class => \App\Http\Middleware\ValidateCsrfToken::class,
+ ],
+ append: [
+ \App\Http\Middleware\UserLastActive::class,
+ ],
+ );
$middleware->api(prepend: []);
$middleware->alias([
'auth' => Authenticate::class,
diff --git a/config/sanctum.php b/config/sanctum.php
index b5f91d64..cf2681f0 100755
--- a/config/sanctum.php
+++ b/config/sanctum.php
@@ -73,7 +73,7 @@ return [
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
- 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
+ 'validate_csrf_token' => \App\Http\Middleware\ValidateCsrfToken::class,
],
];
diff --git a/resources/js/bootstrap.ts b/resources/js/bootstrap.ts
index c4bb7cde..e3cd194c 100644
--- a/resources/js/bootstrap.ts
+++ b/resources/js/bootstrap.ts
@@ -9,6 +9,7 @@ import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
+window.axios.defaults.xsrfCookieName = import.meta.env.VITE_APP_NAME + '_XSRF-TOKEN';
/**
* Echo exposes an expressive API for subscribing to channels and listening