2016-10-08 30 views
1

因此,我有一個提供用戶登錄的API,如果用戶成功登錄,登錄API將返回一個Json Web令牌。Laravel 5.3中間件:創建用於身份驗證的中間件

我會在前端使用登錄API,一切都很順利,我得到了Json Web令牌。 但是,我也想使用laravel auth中間件,因爲只有真正的用戶(具有令牌的用戶)可以移動到另一個頁面。 (是的,我正在使用路線組)。

這是我的路線:

// Login 
Route::get('/tera/admin/login', 'Backend\Login\[email protected]'); 

Route::group(['middleware' => 'auth'], function() { 
    // Logout 
    Route::get('/tera/admin/dologout', 'Backend\Logout\[email protected]'); 

    // Dashboard 
    Route::get('/tera/dashboard', 'Backend\Dashboard\[email protected]'); 

    // Inventory 
    Route::get('/inventory', 'Backend\Inventory\[email protected]'); 
}); 

這種方法,中間件總是重定向我進建在登錄頁面laravel。

解決這種情況的最佳做法是什麼?

謝謝。

+0

你的用戶模型看起來是什麼樣的(它使用什麼特性?) – Kyslik

+0

我正在使用Lumen創建API,所以我的API將直接嘗試進入API並返回true或false –

回答

0

您需要更改Illuminate\Routing\Router.php文件中Authentication Routesauth()方法。在Laravel 5.3,該auth()方法定義了以下路線:

public function auth() 
{ 
    // Authentication Routes... 
    $this->get('login', 'Auth\[email protected]')->name('login'); 
    $this->post('login', 'Auth\[email protected]'); 
    $this->post('logout', 'Auth\[email protected]'); 

    // Registration Routes... 
    $this->get('register', 'Auth\[email protected]'); 
    $this->post('register', 'Auth\[email protected]'); 

    // Password Reset Routes... 
    $this->get('password/reset', 'Auth\[email protected]'); 
    $this->post('password/email', 'Auth\[email protected]'); 
    $this->get('password/reset/{token}', 'Auth\[email protected]'); 
    $this->post('password/reset', 'Auth\[email protected]'); 
} 

所以,你可以在此功能,或者在你的routes文件進行更改,您可以使用auth前綴重寫它們:

Route::group(['prefix' => 'auth', 'middleware' => 'auth'], function() { 
    Route::get('login', 'Backend\Login\[email protected]'); 
    //Define rest of your routes here... 
}); 

或者,您可以導航到app\Http\Controllers\Auth目錄,您將在其中看到處理認證的不同控制器。您將在此目錄中看到LoginController.phpRegisterController.php。這兩個控制器都包含屬性$redirectTo,該屬性定義了用戶登錄後重定向到的位置。將此屬性更改爲所需的路由,並且應該重定向到新路由。

+0

用戶登錄auth已完成在API中,所以前端只會得到返回結果(如用戶令牌和用戶詳細信息) –

相關問題