Reputation: 15
i am trying to start a simple API with Laravel Passport.
i am following this tutorial
i have sucessfully completed it, however when i try accessing "http://localhost:8000/api/CEO" in a browser without specifying a bearer token, i am getting the error:
Symfony\Component\Routing\Exception\RouteNotFoundException Route [login] not defined.
now i understand bearer token is needed to authenticate requests, but how can i verify that the api requests have a token? and if they dont, show an error. Instead of redirecting to a login page that doesn't exists.
Upvotes: 0
Views: 487
Reputation: 2196
If you take a look at laravel git repository you will find the Authenticate.php
middleware: https://github.com/laravel/laravel/blob/8.x/app/Http/Middleware/Authenticate.php
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
What's happening at your end is that you are missing a very important header in your request Accept: application/json
, therefore Laravel is trying to redirect to the login page which is not defined in your api.php
routes.
Just hit your endpoint with postman or something similar by adding that header and you will receive an Unauthenticated
error message.
If you want to open that URL from your browser you can also add a middleware to process the request and return a 401
error message.
I made my own middleware wich attaches the token sent by URL to my request headers.
If no token is present in URL then abort by throwing a 401
error
<?php
namespace App\Http\Middleware;
use Closure;
class ParseTokenFromUrl
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->has('access_token') && !$request->headers->get('Authorization')) $request->headers->set('Authorization', 'Bearer ' . $request->get('access_token'));
if (!$request->headers->get('Authorization')) abort(401);
return $next($request);
}
}
Please also refer to Laravel Passport Route [login] not defined
Upvotes: 1
Reputation: 15
The "auth:api" middleware in api.php corresponds to App/Http/Middleware/Authenticate.php
.
(this is verifiable by checking $routeMiddleware in App/Http/Kernel.php
)
in this middleware we check :
if (! $request->expectsJson()) { return route('login'); }
change the return to
return abort(502, 'Invalid request');
to instead show an error.
Upvotes: 0