Add default Origin header for HTTP requests when testing apps #1599
rdehnhardt
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
When testing applications that use Laravel Sanctum in
statefulApimode, Pest tests fail to authenticate stateful requests because the HTTP client does not include theOriginorRefererheaders by default.This causes Sanctum’s
EnsureFrontendRequestsAreStatefulmiddleware to not recognize the request as coming from a “first-party” frontend, since the following check fails:In a test environment, both values are
null, leading to unexpected authentication failures even when the application is correctly configured.Current Workaround
Developers currently need to manually add the header in every test:
Or globally in
Pest.php:While this workaround is effective, it adds unnecessary boilerplate to every Sanctum-based test suite.
Proposed Solution
Pest could automatically inject a default
Originheader for all HTTP requests made via$this->get(),$this->postJson(),$this->putJson(), etc.The default value could be configurable via an environment variable, for example:
If no value is provided, Pest could fall back to
http://localhost.Benefits
EnsureFrontendRequestsAreStatefulissues in tests.Potential Considerations
The header injection should only happen if the request does not already include an
OriginorReferer.This feature could be optional and toggled via a configuration flag, such as:
Example Behavior
Before:
Sanctum requests fail because no
Originheader is present.After:
Sanctum recognizes the request as coming from
http://localhost, and stateful authentication works automatically.Environment
Summary
This small improvement would make Pest tests work seamlessly with Sanctum’s stateful authentication mode out of the box, reducing friction for developers and improving the overall testing experience.
Thanks for considering this enhancement! 🙌
Beta Was this translation helpful? Give feedback.
All reactions