Skip to content

Commit 3d0629c

Browse files
committed
blacklist routes from CSRF middleware
1 parent 12ddf85 commit 3d0629c

3 files changed

Lines changed: 30 additions & 5 deletions

File tree

app/sprinkles/core/config/default.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,15 @@
5151
'name' => 'csrf',
5252
'storage_limit' => 200,
5353
'strength' => 16,
54-
'persistent_token' => true
54+
'persistent_token' => true,
55+
// A list of url paths to ignore CSRF checks on
56+
'blacklist' => [
57+
// URL paths will be matched against each regular expression in this list.
58+
// Each regular expression should map to an array of methods.
59+
// Regular expressions will be delimited with ~ in preg_match, so if you
60+
// have routes with ~ in them, you must escape this character in your regex.
61+
// Also, remember to use ^ when you only want to match the beginning of a URL path!
62+
]
5563
],
5664
'db' => [
5765
'default' => [

app/sprinkles/core/src/Core.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,21 @@ public function onAddGlobalMiddleware(Event $event)
4040
// See https://github.com/laravel/framework/issues/8172#issuecomment-99112012 for more information on why it's bad to hit Laravel sessions multiple times in rapid succession.
4141
$request = $this->ci->request;
4242
$path = $request->getUri()->getPath();
43+
$method = $request->getMethod();
4344

44-
$csrfBlacklist = [
45-
$this->ci->config['assets.raw.path']
46-
];
45+
$csrfBlacklist = $this->ci->config['csrf.blacklist'];
46+
47+
$isBlacklisted = false;
48+
49+
foreach ($csrfBlacklist as $pattern => $methods) {
50+
$methods = array_map('strtoupper', (array) $methods);
51+
if (in_array($method, $methods) && $pattern != '' && preg_match('~' . $pattern . '~', $path)) {
52+
$isBlacklisted = true;
53+
break;
54+
}
55+
}
4756

48-
if (!$path || !starts_with($path, $csrfBlacklist)) {
57+
if (!$path || !$isBlacklisted) {
4958
$app = $event->getApp();
5059
$app->add($this->ci->csrf);
5160
}

app/sprinkles/core/src/ServicesProvider/ServicesProvider.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,14 @@ public function register(ContainerInterface $container)
239239
$config['site.uri.public'] = trim($public, '/');
240240
}
241241

242+
// Add asset URLs to the CSRF blacklist
243+
$csrfBlacklist = $config['csrf.blacklist'];
244+
$csrfBlacklist['^' . $config['assets.raw.path']] = [
245+
'GET'
246+
];
247+
248+
$config->set('csrf.blacklist', $csrfBlacklist);
249+
242250
if (isset($config['display_errors'])) {
243251
ini_set("display_errors", $config['display_errors']);
244252
}

0 commit comments

Comments
 (0)