laravel8, sanctum, rest, api, authorization, bearer, browser, firefox, xdebug, vscode
For browser (Firefox) install xdebug-helper.
Make a GET request to you API endpoint. By default, Laravel expect a header similar to: "Authorization: Bearer 9CvU9j...0A", which is the reason behind the 403 status.
... http://myapp/api/items?bearer=9CvU9jq23vvaDkYZa9Z3Pr7TN9x1CBNH00slMY0A
... ... 403 Forbidden
Sanctum token create
// Laravel > Register/Login > Dashboard > API tokens > Create API token
// ... Name .......... TOKEN_1
// ... Permissions ... create [Y] read [Y] update [Y]
// ... Create
//
// ... 9CvU9jxxx0A ...... Laravel shows the plain text value of the token before saving it the database. Keep this value safe.
// ... 3d08fexxxdd ...... Then the token is persisted in table personal_access_tokens/token encrypted with SHA256
If you don't want to send the token with every request, open the .env file and add: BEARER_TOKEN=9CvU9j...0A.
BEARER_TOKEN=9CvU9jq23vvaDkYZa9Z3Pr7TN9x1CBNH00slMY0A
Open vendor/laravel/framework/src/Illuminate/Http/Concerns/InteractsWithInput.php:
/**
* Get the bearer token from the request headers.
*
* @return string|null
*/
public function bearerToken()
{
$header = $this->header('Authorization', '');
// Here: Paste this conditional statement to check for bearer token inside the request content.
if ((env('APP_ENV') == 'local') && env('BEARER_TOKEN')) {
return $this->get('bearer')
? $this->get('bearer')
: env('BEARER_TOKEN');
}
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
Make the GET request again. This time the endpoint will work as usual. If you don't want to send the token with every request, open .env file and add: BEARER_TOKEN=9CvU9j...0A.
... http://myapp/api/items?bearer=9CvU9jq23vvaDkYZa9Z3Pr7TN9x1CBNH00slMY0A
... ... { "data": [ {1}, {2}, {3} ] }
... http://myapp/api/items
... ... { "data": [ {1}, {2}, {3} ] }
Advantages:
- use of browser based XDEBUG extension behaviour with vscode; the browser takes care of sending the right cookie value to allow for regular code breakpoints in vscode
- dd() function will render normally; when using something like curl, the dd() output is not usefull at all
Drawbacks:
- because the code modifies a laravel vendor file, it will be rewritten every time we run $(composer install). This is not so bad since the change happens only once in a stable development environment.