Only Allow content type json on POST requests in laravel

Viewed 3960

I am building a laravel API and i need to be able to only accept requests of type 'application/json' when data is being posted. Any other content-types should return a 406 'Not Acceptable' response.

I am aware I could put in some middleware to check for this however I was wondering if there is a better way this could be accomplished?

Thanks

3 Answers

Use this middleware:

class WeWantJsonMiddleware
{
    /**
     * We only accept json
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->isMethod('post')) return $next($request);


        $acceptHeader = $request->header('Accept');
        if ($acceptHeader != 'application/json') {
            return response()->json([], 406);
        }

        return $next($request);
    }
}

(modification of https://stackoverflow.com/a/44453966/2311074)

And add it in App\Http\Kernel to $middleware to check for every post request. If you only want to check for API posts request, just put it in $middlewareGroups['api'].

Simple use middleware like this:

class OnlyAcceptJsonMiddleware
{
    /**
     * We only accept json
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
       // Verify if POST request is JSON
        if ($request->isMethod('post') && !$request->expectsJson()) {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        return $next($request);
    }
}

Here's my two cents:

class JsonMiddleware
{
    /**
     * Accept JSON only
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $header = $request->header('Accept');
        if ($header != 'application/json') {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        if (!$request->isMethod('post')) return $next($request);

        $header = $request->header('Content-type');
        if (!Str::contains($header, 'application/json')) {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        return $next($request);
    }
}
Related