Skip to content

Commit 541ae6d

Browse files
committed
Readme
1 parent eb79900 commit 541ae6d

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

README.md

+52-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ composer require binarcode/laravel-stateless-session
2323
```
2424

2525
## Usage
26-
2726
1. Trigger session, make a GET request to: `/api/csrf-header`. This will return a header with the session key and an optional header with CSRF token `XSRF-TOKEN`.
2827
The header name could be configured in: `stateless.header`
2928

@@ -39,7 +38,6 @@ use Binarcode\LaravelStatelessSession\Http\Middleware\StatelessVerifyCsrfToken;
3938
StatelessVerifyCsrfToken::class,
4039
]);
4140
```
42-
4341
You can create a middleware group in your Http\Kernel with these 2 routes as:
4442

4543
```php
@@ -76,6 +74,58 @@ stateless.header => env('STATELESS_HEADER', 'X-STATELESS-HEADER')
7674
```
7775

7876
Danger: The key name separators should use `-` not `_` [according with this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
77+
78+
### Real use case
79+
80+
Let's say you want to allow visitors to submit a newsletter form. You want also to protect your API with CSRF.
81+
82+
You can setup a GoogleRecaptcha for that, but that's so annoying.
83+
84+
Solution:
85+
86+
Vue newsletter page:
87+
88+
```js
89+
// Newsletter.vue
90+
{
91+
async created() {
92+
const response = await axios.get(`${host}/api/csrf-header`);
93+
this.csrfToken = response.headers['XSRF-TOKEN'];
94+
this.sessionKey = response.headers['LARAVEL-SESSION'];
95+
},
96+
methods: {
97+
98+
async subscribe() {
99+
await axios.post(`${host}/api/newsletter`, {email: '[email protected]'}, {
100+
headers: {
101+
'LARAVEL-SESSION': this.sessionKey,
102+
'X-CSRF-TOKEN': this.csrfToken
103+
}
104+
});
105+
}
106+
107+
}
108+
}
109+
```
110+
111+
`api.php`
112+
113+
```php
114+
Route::post('api/subscribe', function (Request $request) {
115+
116+
// at this point the CSRF token is verified
117+
118+
Subscribers::createFromEmail($request->get('email'));
119+
120+
return response('', 201)->json();
121+
122+
})->middleware([
123+
StartStatelessSession::class,
124+
VerifyHeaderCsrfToken::class,
125+
]);
126+
127+
```
128+
79129
### Testing
80130

81131
``` bash

src/Http/Middleware/StatelessStartSession.php

+1
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ protected function addHeaderToResponse(Response $response, Session $session)
5858
{
5959
if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
6060
$response->headers->set($session->getName(), $session->getId(), true);
61+
$response->headers->set('Access-Control-Expose-Headers', [$session->getName(), 'XSRF-TOKEN'], true);
6162
}
6263
}
6364
}

0 commit comments

Comments
 (0)