如何从 PHP 验证 RESTful JWT API

How to authenticate a RESTful JWT API from PHP

我有一个由 JWT 控制的 Laravel RESTful API,我想从另一条路线对其进行身份验证。这是代码:

//Route.php
Route::group(['prefix' => 'api'], function() {
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
    Route::get('authenticate/user', 'AuthenticateController@getAuthenticatedUser');
});

Route::get('/login', 'LoginController@index');

//Login.blade.php
<form action="http://domain.dev/api/authenticate" method="post">
<input type="text" name="email">
<input type="password" name="password">
</form>

现在因为我使用的是 JWT,所以我得到了一个需要存储在 cookie 中的令牌。然后,一旦用户登录,他们应该被重定向到另一个视图,并且用户将在每次请求时将此令牌作为 header 发送。

我在谷歌上搜索了很多,但找不到任何实际展示如何从 PHP 而不是 JS 框架发出正确请求的教程。

编辑:我现在正在使用 Guzzle 和 OAuth2。这是我提出的请求,但它引发了错误:

    // This request works and it is just a simple route that returns a user.
        $client = new Client();
                $request = $client->createRequest('GET', 'http://example.dev/user');
                $response = $client->send($request);
                dd($response);

    // This one doesn't work, I don't know why. I have confirmed that the request
    // does send the post fields but the api responds with a 500. Although it does
    // work with POSTMAN. I have also tried sending it as Header but still doesn't work

        $client = new Client();
            $response = $client->post('http://example.dev/oauth/access_token', [
                'body' => [
                    'grant_type' => 'password',
                    'client_id' => '1',
                    'client_secret' => '12345',
                    'username' => 'user@gmail.com',
                    'password' => 'password123',
                ]
            ]);
            dd($response->json());

通常,您应该 API 外部。你有你的业务逻辑,然后你公开一个 API 来处理它。没关系。但是,如果您在同一个 Laravel 项目中工作,那么 "call the API" 就没有任何意义,就像外部应用程序所做的那样:您已经在您的项目上下文中了!

你应该使用 Guzzle 之类的东西来调用你的 API 就像外部服务一样,但是你会让你的服务器做两次作品。

我会做什么

如果在我的项目中工作"internally",我会不会使用APIs。它们是为其他外部应用程序创建的接口。不适用于应用程序本身。 :)

你能做什么

所以,即使我不建议你这样做,但要考虑你的行动,这里有一个解决方案。

你可以使用 Guzzle.

更多信息:

如您所见,您可以自由设置您的 headers 并根据您的需求创建完美的请求,但这没有任何意义。

显然您不能在内部使用会话,因为您使用的是基于令牌的身份验证系统。因此,使用中间件将您的 cookie 注入到 "internal" 请求中,然后照常使用它。

这里有一个中间件 handle 方法 body 的例子。您可以使用 merge 方法将您选择的数组与现有请求数据合并。

public function handle(Request $request)
{
    // getting the token
    $token = $request->cookie('token');

    // inject your token in the current request
    $request->merge(['token' => $token]);
}

不要忘记添加一些验证数据,以确保令牌存在并且您可以使用它。

希望对您有所帮助!

编辑:只是为了一个完整的答案......如果你不知道如何创建一个中间件,check this out