2

我在控制器(Laravel 5.2)中使用 auth:api 中间件。

class RestfulController extends Controller
    {

        public function __construct() {
            $this->middleware(['api', 'auth:api'], ['except' => ['login'] ]);
        }

    }

路线:

Route::group(['prefix' => 'api'], function () {
    Route::get('/login', ['uses' => 'RestfulController@login', 'as'=>'login']);
    Route::get('/list', ['uses' => 'RestfulController@list', 'as'=>'list']);
});

如果请求不包含或包含无效的 api_token 框架重定向到登录页面。相反,我想返回带有错误的 JSON 响应。如何实施?

4

2 回答 2

4

更改 app/Http/Middleware/Authenticate.php 处理方法,它会响应 json

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax() || $request->wantsJson()) {
            return response('Unauthorized.', 401);
        } else {
            $response = [
                'status' => 'error',
                'message' => 'This is error message'
            ];
            return Response::json($response);
        }
    }

    return $next($request);
}
于 2016-04-10T12:22:56.237 回答
1

您应该检查中间件组apiauth:api寻找女巫正在做的事情。如果它在供应商包中,则需要对其进行扩展并进行更改。

于 2016-04-10T12:12:48.593 回答