Reputation: 3
I have a livewire component that needs to send requests using JWT.
As the livewire GET
request is not sending the token by default, I decided to modify the Laravel's Authentication middleware in order to send the token that I put in session in the livewire component, via bearer in Laravel Auth middleware.
That the variable that I added to the session in my livewire component, returns NULL when I try to retrieve it in the Authentication middleware.
1.Livewire component
<?php
namespace App\Http\Livewire;
class HelloWorld extends Component
{
public function mount(TransactionCheckoutRequest $request)
{
session(['x__livewire__token' => 'put token in session' ]);
}
}
2.Laravel auth middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Cookie;
class Authenticate extends Middleware
{
public function handle($request, Closure $next, ...$guards)
{
# Check if request is made using LIVEWIRE
if ( request()->hasHeader('x-livewire') ) {
/**
* get token from session
*
*
* But, this $token return NULL
* instead token value.
*/
$token = session()->get('x__livewire__token');
$request->headers->set('Accept', 'application/json');
$request->headers->set('Content-Type', 'application/json');
// # Send token to request header
$request->headers->set('Authorization', 'Bearer ' . $token);
}
# After that, authenticate livewire request
$this->authenticate($request, $guards);
return $next($request);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if ( !$request->expectsJson() ) {
return route('user.login');
}
}
}
3.Web route file
<?php
Route::group(['prefix' => 'v1'], function() {
Route::group(['middleware' => ['auth:api', 'jwt.verifyer', 'hostname.access.verifyer']], function() {
# Here is LIVEWIRE component
Route::get('/processing', HelloWorld::class)->name('transaction.checkout');
});
});
Can somebody explain how should I extend the middleware to use the token?
Upvotes: 0
Views: 1188
Reputation: 1
Livewire uses its own request when making requests. if you want to send additional data. You can send it using addHeaders.
<script type="text/javascript">
document.addEventListener("livewire:load", function(event) {
Livewire.addHeaders({
'Authorization': 'Bearer {{ $token }}',
})
});
</script>
Upvotes: 0