Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

produktive's avatar

Can I use Laravel Sanctum session cookies in a browser extension?

Sanctum session auth is designed for SPA to avoid using JWT. I would also like to use session auth in cookies for my browser extension. One limitation of this method is that the origin of requests must be the same domain or subdomain of the Laravel application. When testing in Insomnia API routes, everything looks good. However, I am able to control the Origin header there. From my browser extension, there is no domain and I cannot change the origin header. Is it possible to use Sanctum cookie auth from the browser extension? I am having a hard time finding examples.

1 like
2 replies
produktive's avatar
produktive
OP
Best Answer
Level 1

I think I have achieved success. I will continue building and see if I run into any roadblocks. But my extension can now get CSRF Token, login, and hit API endpoints.

The extension manifest.json (V3) must contain:

"permissions": [
		"cookies",
		"declarativeNetRequest"
	],
	"declarative_net_request": {
		"rule_resources": [
			{
				"id": "ruleset_1",
				"enabled": true,
				"path": "rules.json"
			}
		]
	},
	"host_permissions": [
		"https://example.test/*"
	],

The rules.json must contain:

[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [
        {
          "header": "Origin",
          "operation": "set",
          "value": "https://example.test"
        }
      ]
    },
    "condition": {
      "urlFilter": "||example.test",
      "resourceTypes": [
        "xmlhttprequest"
      ]
    }
  }
]

And the auth code must be in an extension script, such as background or popup.

const userInfo = async () => {
		const response = await fetch('https://example.test/sanctum/csrf-cookie');
		if (response.ok) {
			const xsrfToken = await chrome.cookies.get({url: 'https://example.test', name: 'XSRF-TOKEN'});
			const login = await fetch('https://example.test/api/login', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					'X-XSRF-TOKEN': decodeURIComponent(xsrfToken.value)
				},
				body: JSON.stringify({
					email: '[email protected]',
					password: 'password'
				})
			});
			return (await fetch('https://example.test/api/user')).json();
		} else {
			return JSON.stringify({error: 'Failed to fetch data: ' + response.statusText});
		}
	}

	userInfo().then(data => console.log('User info', data));

Please or to participate in this conversation.