27

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.

zessx
  • 68,042
  • 28
  • 135
  • 158
  • Are you using https://github.com/tymondesigns/jwt-auth for this? – Matthew Daly Nov 07 '17 at 13:04
  • Laravel doesn't have a built-in method to get this for you, but there's many packages you can use if you don't want to parse the string yourself (of course if you use a package it's not because you don't want to parse a string but because it also has other functionality which you need). – apokryfos Nov 07 '17 at 13:05
  • @MatthewDaly no I am not using that package since I cant make it work with rs256 encryption for some reasons. I am using firebase to sign and veryfy tokens using public/private keys –  Nov 07 '17 at 13:10

6 Answers6

86

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).

Barnabas Kecskes
  • 1,861
  • 17
  • 24
  • that would be awesome if it really exists –  Nov 27 '17 at 15:05
  • 2
    It does exist. [Request Bearer Token](https://laravel.com/api/5.5/Illuminate/Http/Request.html#method_bearerToken) – Isaiahiroko Jan 20 '18 at 07:08
  • I too verified, bearerToken() method is available from Laravel version 5.2 – Rubanraj Ravichandran Nov 01 '18 at 14:51
  • 1
    Did anybody care how to **set** the bearer token within your PHPUnit tests? For those interested when within the PHUnit test menthod add the following: `$actual = $this->call('GET', '/the-api-uri', [], [], [], ['HTTP_Authorization' => 'Bearer ' . $token]);` See more explanations [here](https://laracasts.com/discuss/channels/testing/laravel-testig-request-setting-header) in MarkRedeman's answer. – Valentine Shi Jun 14 '19 at 15:19
  • 1
    As of Laravel 8, the method exists, and it works – kamasuPaul Feb 10 '21 at 07:31
  • I confirm. As of Lumen 8, it exists. I am sure it would exist in Laravel too as @kamasuPaul has confirmed. – Jagadish Nallappa Aug 16 '21 at 15:14
  • Wow, it worked like a charm, thank you so much for saving so much of my time. – Avdhesh Solanki Jan 13 '23 at 05:45
19

To Get the Bearer token from Header in API call, I used below method. It is working for me in Laravel 6.6.0

$token= request()->bearerToken();

Hope this will work for you.

Used in Laravel 6.6.0

Note: If BearerToken not showing, Then please Cross Check if the bearerToken is available in header or not..

$header = $this->header('Authorization', '');        
if (Str::startsWith($header, 'Bearer ')) 
{            
     return Str::substr($header, 7);        
}
Chandan Sharma
  • 2,321
  • 22
  • 22
  • Please check you have added `use Illuminate\Http\Request;` Its working fine in Laravel 6.6.0 @QumberRizvi – Chandan Sharma Feb 06 '20 at 11:32
  • For me this is working locally but not in production, no idea why, the `$request->bearerToken()` is null, the whole `Authorization` header actually. Any ideas? – Marcos Di Paolo Mar 11 '20 at 16:01
  • Please Check ```use Illuminate\Http\Request``` is using or not & the laravel version. If any Issue please Send your Code. @Marcos – Chandan Sharma Mar 17 '20 at 19:20
  • I get empty bearer even though I see it in the request... – trainoasis Dec 11 '20 at 09:59
  • You can crosscheck by using also ```$header = $this->header('Authorization', ''); if (Str::startsWith($header, 'Bearer ')) { return Str::substr($header, 7); } ``` If the Header response contain the Authorization data or not. – Chandan Sharma Dec 14 '20 at 08:50
2

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);
       }
  }
Plabon Dutta
  • 6,819
  • 3
  • 29
  • 33
1

You may do something like:

$response = explode(':', $request->header('Authorization'));
$token = trim($response[2]);
Raza Mehdi
  • 923
  • 5
  • 7
0

if you use auth:api don't need set guard name 'api'

\Auth::guard('api')->getTokenForRequest();
the_hasanov
  • 782
  • 7
  • 15
0
if($apiKey = getallheaders()['Authorization'] ?? null) {
    $apiKey = str_replace(["Bearer", "bearer", " "], "", $apiKey);
}
user1730452
  • 155
  • 1
  • 8