如何使用 access_token 通过 Laravel 5.4 验证 SPA

How to use access_token to authenticate SPA with Laravel 5.4

我正在尝试使用我的 Laravel 5.4 应用程序验证我的单页应用程序(用 Marionette 编写)。根据我以前的经验,SPA 会:

不幸的是,我正在努力理解如何在 Laravel 5.4 中实现这一目标。

我需要使用 Passport 吗?我真的不认为我需要 OAuth2,但 Passport 是否也提供简单的 token-based 身份验证?看起来,我已经从 /oauth/token 端点获得了上述预期的令牌,但我不知道如何使用此令牌。我什至不认为它是为了这个目的。

我尝试在 header 中使用此令牌向 /api/user 发送请求,将其发布并作为查询字符串,但没有成功。同样让我担心的是 Laravel 中的 expires_in(31536000 秒 = 365 天),这似乎太长了。我担心这个 Passport OAuth 令牌实际上用于 OAuth2 访问,而不是我习惯的 1-day-ish 过期访问令牌。

我也读到了 Laravel 的 TokenGuard,但这似乎是某种奇怪的令牌,存储在 user [=65] 的 api_token 列中=],我的心态完全错了。例如,它不会过期,并且它是 per-user 而不是 per-user-session,这意味着必须从多个设备使用相同的令牌。等等

非常困惑...感谢任何帮助!

您可以尝试 JWT,本教程可能会对您有所启发:https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

我实际上最终使用了 Passport,基于在 https://laracasts.com/discuss/channels/code-review/api-authentication-with-passport?page=1&replyId=282168:

找到的一些非常有用的代码

routes/api.php

Route::post('auth/token', 'Api\Auth\DefaultController@authenticate');
Route::post('auth/refresh', 'Api\Auth\DefaultController@refreshToken');

app/Http/Controllers/Api/Auth/DefaultController.php

<?php

namespace App\Http\Controllers\Api\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

class DefaultController extends Controller
{
    /**
     * @var object
     */
    private $client;

    /**
     * DefaultController constructor.
     */
    public function __construct()
    {
        $this->client = DB::table('oauth_clients')->where('id', 2)->first();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function authenticate(Request $request)
    {
        $request->request->add([
            'username' => $request->username,
            'password' => $request->password,
            'grant_type' => 'password',
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
            'scope' => '*'
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        return Route::dispatch($proxy);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    protected function refreshToken(Request $request)
    {
        $request->request->add([
            'grant_type' => 'refresh_token',
            'refresh_token' => $request->refresh_token,
            'client_id' => $this->client->id,
            'client_secret' => $this->client->secret,
        ]);

        $proxy = Request::create(
            '/oauth/token',
            'POST'
        );

        return Route::dispatch($proxy);
    }
}