In Laravel 5, I wrap my API routes in a route group like this:
1 2 3 |
Route::group(['middleware' => ['auth:api','throttle']], function() { // API routes here }); |
Notice that I use auth:api and throttle on my middleware array.
auth:api turns on the auth middleware with API token as guard, while throttle activates rate limiter for APIs.
To get started with API token authentication, you may read https://gistlog.co/JacobBennett/090369fbab0b31130b51.
I followed the same tutorial to set mine up, but had this issue: Upon using invalid api_token or no token at all, I am redirected to the /login
route, which in my case is a currently nonexistent route.
As instructed by the guide, I already edited my app/Http/Middleware/Authenticate.php
file to add the || $request->wantsJson()
condition, but my API routes still redirected to /login route upon detection of invalid api_token.
The solution
What I did was add another condition: || $guard == "api"
And now, my app/Http/Middleware/Authenticate.php
file looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($request->ajax() || $request->wantsJson() || $guard == "api") { return response('Unauthorized.', 401); } else { return redirect()->guest('login'); } } return $next($request); } } |