簡體   English   中英

Laravel Passport 路由 [登錄名] 未定義

[英]Laravel Passport Route [login] not defined

我使用 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

如果用戶未通過身份驗證,我想不要重定向到任何頁面,只看到該頁面

使用 Postman 並設置 Header Accept: application/json否則 Laravel Passport 永遠不會知道它是一個 API 客戶端並因此重定向到 Web 的 /login 頁面。

請參見下圖以了解設置接受參數的位置: 在此處輸入圖像描述

您是否直接在瀏覽器搜索欄中輸入上述網址? 如果你做錯了,因為你還需要在你的請求中輸入 API 令牌__!

檢查請求是否包含令牌或不制作您自己的中間件。

創建中間件的命令

php artisan make:middleware CheckApiToken

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

將中間件處理方法更改為

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', 401);
}

Like This 你的網址應該是這樣的

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

您還必須添加另一個標頭 Key: Accept 和 value: application/json

檢查您的標頭請求

授權 = Bearer {你的令牌}

@Eki的回答中,

此錯誤是因為您沒有在標頭中設置“接受”字段。

為避免此錯誤,請添加優先於 Authenticate 的中間件以檢查:

  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');

您還必須添加另一個標頭 Key: X-Requested-With 和 value: XMLHttpRequest

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM