【问题标题】:Laravel token authenticationLaravel 令牌认证
【发布时间】:2017-04-20 02:04:00
【问题描述】:

我有一个服务于 VueJS 前端的 Laravel API(实际上是一个 Lumen API)。 Vue 应用程序允许用户登录 Google。然后 Google 令牌被发送回 Lumen API,后者通过 Google 验证令牌,然后验证电子邮件地址是否为有效用户。然后它生成一个令牌,将其与用户一起存储在数据库中并返回用户对象。

我没有使用 Passport 或 jwt-auth 或类似的东西。那么现在,我该如何使用默认的 Auth 中间件来验证(现在登录的)用户将在每个请求中返回的令牌标头? (即数据库中的令牌是否已过期?)。有没有办法更有效地做到这一点,让 Laravel 缓存有效的令牌,而不必为每个请求访问数据库?

【问题讨论】:

    标签: laravel api authentication


    【解决方案1】:

    您可以使用Authentication Middleware。将您的请求传递给api_token。更详细的答案可以在here找到。

    api_token 列添加到您的User 表中。

    $table->string('api_token', 60)->unique();
    

    拥有这样的身份验证中间件:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    class Authenticate
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @param  string|null  $guard
         * @return mixed
         */
        public function handle($request, Closure $next, $guard = null)
        {
            if (Auth::guard($guard)->guest()) {
    
                if ($request->ajax() || $request->wantsJson()) {
                    return response('Unauthorized.', 401);
                } else {
                    return redirect()->guest('auth/login');
                }
            }
    
            return $next($request);
        }
    }
    

    并使用Route Group

    Route::group(['middleware' => 'auth:api'], function () {
    
        Route::resource('api/v1/foo/bar', 'API\FooBarController');
    
    }
    

    【讨论】:

    • 感谢您的回复。但是如何通过中间件中的Auth::guard($guard)-&gt;guest() 检查呢?我正在数据库中存储令牌(带有到期日期)。
    • 在你的路由组中,语法是'middleware' =&gt; 'auth:guardName'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多