Search code examples
laravelcorslaravel-passport

Laravel cors throws error when trying to run Request::create


I have a custom login method for my Laravel Passport API.

I am using Request::create to call the /oauth/token endpoint from inside my login method.

The problem is that from within my React project, I am getting a CORS error.

The error ONLY happens when using the login method and I think I have traced it down to the way that the data is being 'returned'

I am using the barryvdh/laravel-cors package and the relevant portion of my login method is as follows;

    $data = [
        'grant_type' => 'password',
        'client_id' => 2,
        'client_secret' => 'ggdfgdvsreckuscenusekubsvbd',
        'username' => $request->email,
        'password' => $request->password,
        'scope' => '',
    ];

    $request = Request::create('/oauth/token', 'POST', $data);

    return app()->handle($request);

Is there a way that I can cast that $request response to a variable and then return it using the standard response->json?

If i return the $request as it is, it doesnt give me any of the data that the return app()->handle($request); line gives me i.e token, refresh token etc etc

I can use all other POST methods in my API except this one.


Solution

  • You can try it this way. Its basically launching a new request from a another request

    $data = [
            'grant_type' => 'password',
            'client_id' => 2,
            'client_secret' => 'ggdfgdvsreckuscenusekubsvbd',
            'username' => $request->email,
            'password' => $request->password,
            'scope' => '',
        ];
    
    $request = app()->make('request');
    $request->request->add($data);
    
    $tokenRequest = Request::create(
                env('APP_URL') . '/oauth/token',
                'post'
            );
    
    return Route::dispatch($tokenRequest);