molerat
molerat

Reputation: 994

Laravel 5.8 / VueJs 2 / Axios GET request does not send cookies (CORS, subdomain)

Setup

We have a server with the domain test.de and two applications A and B running on the same server but on subdomains:

a.test.de
b.test.de

Problem

A sends a GET-request to B's API, but it's always sending the request without cookies, even though it should.

Because the endpoint is protected, we always get 401 Unauthorized back. Requests to unprotected endpoints on B cause no issues, because they don't need the cookies.

Things we have tried:

<?php

return [
    'supportsCredentials' => true,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];

Upvotes: 1

Views: 930

Answers (2)

molerat
molerat

Reputation: 994

It seems we had permission issues on our server which prevented the frontend code from updating and therefore the withCredentials option was not going through.

Whoever has this issue in the future: Please read the question and you will see the things we have tried. It's important to understand that for CORS certain Headers need to be sent back and forth in order to allow cookies to be sent.

Sorry for the buzz....

Upvotes: 1

Screeper
Screeper

Reputation: 158

Try the middleware below... If it doesn't help I'll delete the answer ;)

<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ModifyHeadersMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next( $request );
        if($response instanceof StreamedResponse) {
            $response->headers->set('Access-Control-Allow-Origin', '*' );
            $response->headers->set( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept, Application' );
            $response->headers->set( 'Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS' );
        } else {
            $response->header( 'Access-Control-Allow-Origin', '*' );
            $response->header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept, Application' );
            $response->header( 'Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS' );
        }

        return $response;
    }
}

Upvotes: 0

Related Questions