1
votes

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)

3
Just to make sure we all see the code, please include middleware code you are using and tell us version you use (master or develop)? - Marcin Nabiałek
The middleware was an ACL implementation of mine. I just added a code like var_dump($request->headers()->all()); exit(); to see what headers are present. and I'm using the master branch of 5.2 - Milad.Nozari

3 Answers

1
votes

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.

0
votes

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

0
votes

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