mercredi 2 mars 2016

Laravel + Dingo + JWT + cors and OPTIONS method

On my Laravel installation, I have set up Dingo API along with JWT-Auth by tymondesigns and Laravel-cors by barryvdh.

This is the process of logging in and retrieving data from the front end (which is hosted on a different server):

  1. POST credentials to the API
  2. receive JWT token, which is then stored in localStorage with Bearer key in front. After this point, the interceptor automatically gets and sets the Authorization header with JWT token.
  3. POST request is sent to /users/me, which is just a route to retrieve the user data. The user data comes with username, email, permissions and messages at the moment. messages is an Eloquent model where User::class basically hasMany(Message::class). By the way, the method that retrieves the user data, reads the user using $user = JWT::parseToken()->authenticate(); and then I'm using Dingo's $this->response()->item($user, new SelfTransformer()); to send the data back.

So at this point everything seems to be working fine. The user is logged in, the user object is populated with all the necessary stuff, and the messages table is populated with messages.

I am paginating the messages, so at the moment I am receiving just 1 message at a time.

Now the issue is that after this point (after the user object is retrieved), if I make another request, let's say to the /users/me?messages=2 to retrieve the second page of messages, I get the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I get the same error if I try to log out as well.

I even get the same error if I try to register with already registered user.

So it feels like every single time there is an exception thrown in Laravel, Access-Control-Allow-Origin header is no longer set.

This is my cors configuration:

return [
    /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |

     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => true,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'Accept', 'Authorization', 'X-Requested-With', 'Origin'],
    'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    'exposedHeaders' => ['Authorization'],
    'maxAge' => 0,
    'hosts' => [],
];

If I use Postman, it all works fine.

Also, I noticed that in my network tab, there are 2 requests being set all the time. One has method set to OPTIONS and the second one is the actual request...

I am getting depressed...



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire