3

I am programming a Laravel 5.1 RestFUL API, but I have a very strange problem with the middleware and the controller response (is empty always).

Routes:

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

    Route::post('game/add/{id}', 'GameController@addGameToUser');    
});

The middleware is defined in the kernel.php correctly:

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'token.api' => \App\Http\Middleware\TokenMiddleware::class,
    ];

I have removed

\App\Http\Middleware\VerifyCsrfToken::class

from the middlewares globals, because I just use AJAX API calls. ,

In my middleware, I check just I have a Token header param:

Middleware Code:

<?php

namespace App\Http\Middleware;
use Closure;

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

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Origin, Content-Type, Token, Accept, Authorization, X-Request-With');
        header('Access-Control-Allow-Credentials: true');


        $token = $request->header('Token');

        if($token == null)
            return response('Not valid token provider.', 401);

        else
        {
            $next($request);
        }



    }
}

In my controller (GameController), and in the method addGameToUser, I just return a JSON Test value, but the response is always empty (testing with postman). If I remove the middleware from the controller, all works fine... I have no idea why...

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;



use App\Http\Controllers\Controller;
use App\UserGame;

class GameController extends Controller
{
    public function addGameToUser(Request $request, $idGame)
    {
        return response()->json(['status'=>'ok','data'=>'data_example'], 200);
    }

}

Thank you so much!!

3 Answers 3

10

You're not returning anything in handle() if $token isn't null. Try this:

public function handle($request, Closure $next)
{

    header('Access-Control-Allow-Origin: *');
    ...

    $token = $request->header('Token');

    if($token == null) return response('Not valid token provider.', 401);

    // return the $next closure, so other Middlewares can run
    return $next($request);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, too late for programming, I'm going to sleep :D
Just curious what exactly is ` $next($request)`?
2

You forgot to return the response. just add return as below.

return $next($request);

Hope this help.

1 Comment

Thanks, too late for programming, I'm going to sleep :D
0

Don't remove VerifyCsrfToken.php it's used for security purpose.There is some way to avoid CSRF.You can avoid an full route and can also can avoid specific url.For this first go to VerifyCsrfToken.php and edit like this

If want avoid routes try this

//add an array of Routes to skip CSRF check


private $openRoutes = ['free/route', 'free/too'];

//modify this function

public function handle($request, Closure $next)
{
    //add this condition 
foreach($this->openRoutes as $route) {

  if ($request->is($route)) {
    return $next($request);
  }
}

return parent::handle($request, $next);
}

Hope it will work

1 Comment

Better solution to avoid remove VerifyCsrfToken is using: protected $except = [ 'api/*' ]; in the class ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.