Laravel TestCase not sending Authorization headers (JWT Token)

限于喜欢 提交于 2019-12-01 17:46:19

We faced a similar issue when writing tests on Laravel 4.2, exceptionally we added this lines when running the application on the testing environment:

 // This will only work when unit testing
        if ((\App::environment() == 'testing') && array_key_exists("HTTP_Authorization",  LRequest::server())) {
            $headers['Authorization'] = LRequest::server()["HTTP_Authorization"];
        }

I tried the following code in Controller constructor:

if (env('APP_ENV') == 'testing' 
        && array_key_exists("HTTP_AUTHORIZATION", request()->server())) {
    JWTAuth::setRequest(\Route::getCurrentRequest());
} 

There are two ways to send a token to our API, If header is not working simply append to your URL. Example:

 http://api.mysite.com/me?token={yourtokenhere}

So you could do this:

In your TestCase

public function signIn($data=['email'=>'youremail@yahoo.com', 'password'=>'password'])
{
    $this->post('/auth/signin', $data);
    $content = json_decode($this->response->getContent());

    $this->assertObjectHasAttribute('token', $content, 'Token does not exists');
    $this->token = $content->token;

    return $this;
 }

This will grab and store a token in $this->token so you can use it to make a request

Then later in your tests

public function testResticted()
{
    $this->signIn();
    $this->call('GET', '/restricted/page', ['token'=>$this->token], $cookies = [], $files = [], $server = []);
    dump($this->response);
 }
Antony Penn

Apache by default consumes this header. You can fix apache behavior by adding this to your site .conf file:

# Workaround apache consuming the header.
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!