Laravel TestCase not sending Authorization headers (JWT Token)

前端 未结 4 1082
故里飘歌
故里飘歌 2021-01-18 02:46

Summary

We are writing unit tests to test the creation and invalidation of JWT tokens and receiving a \"The token could not be parsed from the reque

相关标签:
4条回答
  • 2021-01-18 03:21

    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);
     }
    
    0 讨论(0)
  • 2021-01-18 03:23

    I tried the following code in Controller constructor:

    if (env('APP_ENV') == 'testing' 
            && array_key_exists("HTTP_AUTHORIZATION", request()->server())) {
        JWTAuth::setRequest(\Route::getCurrentRequest());
    } 
    
    0 讨论(0)
  • 2021-01-18 03:33

    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"];
            }
    
    0 讨论(0)
  • 2021-01-18 03:38

    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]
    
    0 讨论(0)
提交回复
热议问题