jeudi 9 février 2017

Cors Is Needed, but how do I do it with Middle ware in Laravel 5.3?

So I have the following middle ware (similar to this question):

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

}

Seems simple, its registered:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        // ...
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\Cors::class,
        // ...
    ];
}

The route uses it:

Route::group([
    'prefix'     => 'api/v1/',
    'middleware' => 'cors'
], function() {
    // ...
});

So by now we have everything working, great. Excellent. Now lets throw a wrench into our blog api, in the constructor lets do:

public function __construct(BlogsEntity $blogsEntity, BlogService $blogService, BlogValue $blogValue) {
    $this->blogsEntity  = $blogsEntity;
    $this->blogsService = $blogService;
    $this->blogValue    = $blogValue;

    $this->middleware('api.auth', ['only' => ['blogs', 'edit', 'delete']]);
    $this->middleware('api.blog.validation', ['only' => ['create', 'edit']]);
}

Ok so the first middle ware, since we will be calling the blogs method is the api.auth. What does that look like:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.']);
        }


        return $next($request);
    }
}

So you might be thinking, well ya - you are getting the error:

Fetch API cannot load http://ift.tt/2kTDsUc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ift.tt/2k8SpNR' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Because you are not setting CORS on the api auth request. So I did:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ApiAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['status' => 401, 'error_message' => 'You cannot access this route.'])
                ->headers( 'X-Total-Count', 0 );
        }


        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin')
            ->header('Access-Control-Expose-Headers', 'X-Total-Count')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Same issue.

I have middle ware that affects specific routes and I have cors that affects all api routes. So how do I fix this?

I thought I was doing this right, the request coming in for any route, has all the associated headers on them If I remove the middle ware from the constructor, this works perfectly, no issue. If I remove the "only on blogs" part, its works perfectly. No issue.

The Cors middle ware is on every route for the api section. Yet some routes have specific middle ware that are triggered on specific actions that when enabled cause this cors issues, but when disabled do not.

help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire