首页 > 解决方案 > Laravel:使用 Guzzle 使用自定义 Passport 登录的解决方案

问题描述

我正在尝试在控制器内部执行路由/api/user/ signin 以向/oauth/token发送 Guzzle HTTP 帖子。很棒,但服务器停了下来。我发现了这个:https ://stackoverflow.com/a/46350397/5796307

那我该怎么办?如何在没有 HTTP 请求的情况下调用 /oauth/token?我可以“创建”一个请求类并传递给该函数吗?

标签: laravelguzzle

解决方案


无需使用 Guzzle 或 file_get_contents,从控制器函数中创建一个新的 HTTP 请求并通过框架路由它:

public function signin (Request $request) {

    // get an appropriate client for the auth flow
    $client = Client::where([
        'password_client' => true,
        'revoked'         => false
    ])->first();

    // make an internal request to the passport server
    $tokenRequest = Request::create('/oauth/token', 'post', [
            'grant_type'    => 'password',
            'client_id'     => $client->id,
            'client_secret' => $client->secret,
            'username'      => $request->input('email'),
            'password'      => $request->input('password')
    ]);

    // let the framework handle the request
    $response = app()->handle($tokenRequest);

    // get the token from the response if authenticated, other wise redirect to login
}

推荐阅读