Laravel Passport Route [登录]未定义

时间:2018-03-15 08:06:16

标签: php laravel laravel-passport

我使用Laravel护照进行身份验证

路线api.php

Route::get('/todos', function(){
  return 'hello';
})->middleware('auth:api');

但是当打开localhost:8000 / api / todos时,我看到以下错误

 InvalidArgumentException
Route [login] not defined.
 * @return string
 *
 * @throws \InvalidArgumentException
 */
public function route($name, $parameters = [], $absolute = true)
{
    if (! is_null($route = $this->routes->getByName($name))) {
        return $this->toRoute($route, $parameters, $absolute);
    }

    throw new InvalidArgumentException("Route [{$name}] not defined.");
}

/**
 * Get the URL for a given route instance.
 *
 * @param  \Illuminate\Routing\Route  $route
 * @param  mixed  $parameters
 * @param  bool   $absolute
 * @return string
 *
 * @throws \Illuminate\Routing\Exceptions\UrlGenerationException
 */
protected function toRoute($route, $parameters, $absolute)
{
    return $this->routeUrl()->to(
        $route, $this->formatParameters($p

如果用户未经过身份验证,我想要 不要重定向到任何页面,只能看到页面

6 个答案:

答案 0 :(得分:9)

使用Postman并设置Header Accept:application / json,否则Laravel Passport将永远不知道它是API客户端,因此重定向到Web的/ login页面。

答案 1 :(得分:2)

您是否直接在浏览器搜索栏中输入了上述网址? 如果你做错了,因为你还需要输入带有你的请求的API令牌__ !!

要检查请求是否包含令牌,请创建自己的中间件。

创建中间件的命令

php artisan make:middleware CheckApiToken

https://laravel.com/docs/5.6/middleware

chenage中间件方法

public function handle($request, Closure $next)
{
    if(!empty(trim($request->input('api_token')))){

        $is_exists = User::where('id' , Auth::guard('api')->id())->exists();
        if($is_exists){
            return $next($request);
        }
    }
        return response()->json('Invalid Token');
}

喜欢这个 你的网址应该是这样的

http://localhost:8000/api/todos?api_token=API_TOKEN_HERE

答案 2 :(得分:2)

您还必须添加另一个标头键:接受和值:application / json

答案 3 :(得分:1)

检查您的标题请求以放置

  

授权=承载{您的令牌}

答案 4 :(得分:0)

您还必须添加另一个标头键:X-Requested-With和值:XMLHttpRequest

答案 5 :(得分:0)

@Eki答案的下面,

此错误是因为您没有在标题中设置“接受”字段。

为避免此错误,请向“身份验证”添加优先级为中间件,以检查:

  1. 使用以下处理程序添加额外的中间件

    public function handle($request, Closure $next)
    {
        if(!in_array($request->headers->get('accept'), ['application/json', 'Application/Json']))
            return response()->json(['message' => 'Unauthenticated.'], 401);
    
        return $next($request);
    }
    
  2. 在app / Http / Kernel.php中设置优先级

    protected $middlewarePriority = [
        ...
        \App\Http\Middleware\MyMiddleware::class, // new middleware
        \App\Http\Middleware\Authenticate::class,
        ...
    ];
    
  3. 将新的中间件添加到您的路由

    Route::get('/todos', function(){
        return 'hello';
    })->middleware('MyMiddleware', 'auth:api');