Reputation: 878
I have RESTfull api in my appliication using AJAX PUT request like this:
$.ajax({
method: "PUT",
url: "/device/{{ $client->id }}",
async: false,
data: {
javascript_enabled: $('#javascript-enabled').text(),
cookies_enabled: $('#cookies-enabled').text(),
device_pixel_ratio: $('#device-pixel-ratio').text(),
screen_resolution: $('#screen-resolution').text(),
browser_window: $('#browser-window').text(),
local_time: $('#local-time').text(),
local_time_zone: $('#local-time-zone').text(),
_token: "{{ csrf_token() }}"
},
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert( "Internal server error occurred.");
}
});
This code works as it should when I have cookies enabled in browser.
However when I disable cookies I get "TokenMismatchException".
I have solved this by putting this line in "App\Http\Middleware\VerifyCsrfToken" class:
protected $except = [
'device/*'
];
Is there any way of solving this without disabling csrf check for this route?
Upvotes: 1
Views: 391
Reputation: 11310
You can authenticate the token only if you have csrf
token present in your request, if not you shall go alternative way like this
Creating a own token which your application ables to identify it
Like having a parameter something like custom_token
and you shall identify at
app\Http\Middleware\VerifyCsrfToken.php
Tip : If you do print_r($request)
you can see all the elements
You shall Authenticate your custom token like this
$paramExist= $request->custom_token;
#return parent::handle($request, $next);
if(isset($paramExist))
{
$yourSpecialkey ='a2$%$'; #This to check whether the param has the value that you set
if($paramExist==$yourSpecialKey)
{
return $next($request);
}
else
{
return parent::handle($request, $next);
}
}
else
{
return parent::handle($request, $next);
}
I have given you this temporary matching, you shall use your own way to match/authenticate your token.
Upvotes: 1