【问题标题】:Laravel 5.3 Middleware: Create Middleware for authentication purposesLaravel 5.3 中间件:创建用于身份验证的中间件
【发布时间】:2017-02-17 11:59:05
【问题描述】:

所以,我有一个提供用户登录的 API,如果用户成功登录,登录 API 将返回一个 Json Web Token。

我将在前端使用登录 API,一切顺利,我得到了 Json Web Token。 但是,我也想使用 laravel auth 中间件,因为只有真正的用户(具有令牌的用户)才能移动到另一个页面。 (是的,我正在使用路由组)。

这是我的路线:

// Login
Route::get('/tera/admin/login', 'Backend\Login\LoginController@index');

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

    // Dashboard
    Route::get('/tera/dashboard', 'Backend\Dashboard\DashboardController@index');

    // Inventory
    Route::get('/inventory', 'Backend\Inventory\InventoryController@index');
});

使用这种方法,中间件总是将我重定向到 laravel 内置的登录页面。

解决这个案例的最佳实践?

谢谢。

【问题讨论】:

  • 你的用户模型是什么样子的(它使用了什么特征?)
  • 我使用Lumen创建API,所以我的API会直接尝试进入API,并返回true或false

标签: php json laravel authentication jwt


【解决方案1】:

您需要在Illuminate\Routing\Router.php 文件中更改auth() 中的Authentication Routes 方法。在 Laravel 5.3 中,auth() 方法定义了以下路由:

public function auth()
{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}

因此,您可以在此函数或 routes 文件中更改它们,您可以使用 auth 前缀覆盖它们:

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

或者,您可以导航到app\Http\Controllers\Auth 目录,您将在其中看到处理身份验证的不同控制器。您将在此目录中看到 LoginController.phpRegisterController.php。这两个控制器都包含属性$redirectTo,该属性定义了用户登录后重定向到哪里。将此属性更改为您想要的路由,您应该被重定向到新路由。

【讨论】:

  • 用户登录验证已经在 API 中完成,所以前端只得到返回结果(作为用户令牌和用户详细信息)
猜你喜欢
  • 2019-03-15
  • 2021-01-21
  • 2017-02-26
  • 2017-03-15
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 2019-06-12
相关资源
最近更新 更多