I am expecting a JWT token from all the incoming request, and it should be included on request headers like: Authorization => 'Bearer: some token here'
I want to get this token and verify it: here is what I am trying:
$token = $request->header('Authorization');
and this is what I get:
"Authorization: Bearer: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJleGFtcGxlLm9yZyIsImF1ZCI6ImV4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDB9.UQUJV7KmNWPiwiVFAqr4Kx6O6yd69lfbtyWF8qa8iMN2dpZZ1t6xaF8HUmY46y9pZN76f5UMGA0p_CMqymRdYfNiKsiTd2V_3Qpt9LObaLg6rq18j3GLHfdr8nyBzO3v7gTpmNaU6Xy47aMDsbcs593Lx_lD3PnO41oEHgih7CsRKW1WcW1radnpEhdDO7-GpmGOF6xUnpAlQ9EHqpqnIlZPbVoJg92Iwozn-07uuWrkyKUpYN4IPpstd1ks3cKlJ6FH-2ROiC4N0MVLxp4lhUyKhLdwgDWYH4tjtdrEVK0a3_zVtK1ukvriEJqMkfYHnE6Bwv_pv_-lRNy_y7m-YQ"
Question is there any way to grab only the token not including "Authorization: Bearer"
and of course I could parse the whole string and get the token, but I am just wondering if there is another way of getting it without parsing.
There is a bearerToken()
method on the Illuminate\Http\Request
object, so you should be able to just do $token = $request->bearerToken();
and get back what you expect (that's in Laravel 5.5 - I'm not sure of previous versions).
To Get the Bearer token from Header in API call, I used below method.
It is working for me in Laravel 6.6.0
$request = request();
$token = $request->bearerToken();
Hope this will work for you.
Used in Laravel 6.6.0
The method bearerToken()
was introduced Laravel 5.2. You can use:
$token = $request->bearerToken();
to get the token. In case you're planning to get token from a header with a changed text from "Bearer" to something else, you can define your own function like below:
public function bearerToken()
{
$header = $this->header('Authorization', '');
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
You may do something like:
$response = explode(':', $request->header('Authorization'));
$token = trim($response[2]);
if you use auth:api don't need set guard name 'api'
\Auth::guard('api')->getTokenForRequest();