mnVoh February 2016

Can't include Authorization header with Laravel's unit tests

After searching and testing different methods for hours the following seems to be the way to include an authorization header with unit tests inside Laravel 5.2 for jwt-auth:

$this->post(route('share.upload'), [
            'type' => 'video'
        ], ['HTTP_Authorization' => 'Bearer ' . $token])....

What I have tried beside that:

  • Using Authorization instead of HTTP_Authorization
  • putting ['HTTP_Authorization' => 'Bearer ' . $token] inside ['headers' => _HERE_ ]

Also the token is generated correctly and I've used ->dump() to get the output and the exception is :

The token could not be parsed from the request

I dumped the headers in a middleware (that's placed before jwt.auth) and there's an authorization element: authorization

I thought what the heck , maybe it's because of the lower case a!!! But then did the same thing with my rest client(which returns a successful response) but it was just the same.

Any ideas? Thaaaanks

P.S: I've also seen this: Laravel TestCase not sending Authorization headers (JWT Token)

Answers


schellingerht February 2016

You have to check that Apache stripes your Authorization header. So add the following code to your .htaccess to solve this problem:

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Alternative

Of course, you can add the token as URL parameter instead of sending as header.

http://foo.com/page.php?token=YourJWTToken


Marcin NabiaƂek February 2016

You haven't included your middleware class as I asked, so I can only guess.

First of all you should in your test do something like this:

$user = User::find(1); // sample user
$token = JWTAuth::fromUser($user);

$this->post(route('share.upload'), [
            'type' => 'video'
        ], ['Authorization' => 'Bearer ' . $token]);

and in your middleware you need to make sure you don't do simply:

JWTAuth::parseToken()->authenticate();

but

JWTAuth::setRequest($request)->parseToken()->authenticate();

if you don't use setRequest method, your tests will fail also in case if using for example Postman everything works fine.


mnVoh February 2016

Here's how I solved the problem:

  1. In my login method, added a line to save the jwtauth token to a file. But only when env('APP_DEBUG', false) == true;
  2. Instead of using $token = JWTAuth::fromUser($user); to get the token to test the api, I read the token from the file.
  3. Added the file containing the token to .gitignore :-)

Post Status

Asked in February 2016
Viewed 3,762 times
Voted 11
Answered 3 times

Search




Leave an answer