【发布时间】:2019-10-25 12:04:52
【问题描述】:
我正在使用 guzzle HTTP 客户端在用户成功登录后发出基于密码授予的访问令牌。我正在为 oauth 使用护照包,并且我已经完成了所有设置,其中包括它创建的密码授予客户端。在我的登录控制器中,我覆盖了 AuthenticatesUsers 特征的 sendLoginResponse 方法,以便在成功的电子邮件/密码身份验证时发出访问令牌
public function sendLoginResponse(Request $request)
{
try {
Log::debug("Auth attempt sucessful, obtaining access_token for user :: ".$request->email);
$client = new Client();
$token_response = $client->post(config('app.url').'/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('auth.password_grant.client.id'),
'client_secret' => config('auth.password_grant.client.secret'),
'username' => $request->email,
'password' => $request->password,
'scope' => '*',
],
]);
if($token_response->getStatusCode()!=200) {
Log:error("Login failed to generate Access Token");
throw new InvalidCredentialsException();
}
$request->session()->regenerate();
$this->clearLoginAttempts($request);
$data = json_decode((string) $token_response->getBody(), true);
Cookie::queue('refresh_token',$data->refresh_token,config('auth.tokens.refresh.expire.days')*1440);
Log::debug("Adding Bearer token to Authorization header");
return response()->view('dashboard', [
'expires_in' => $data->expires_in
], 200)->header('Authorization', $data->token_type.' '.$data->access_token);
} catch(Exception $e){
Log::error('Error :: '.$e->getMessage());
throw $e;
}
}
当我发出这个帖子请求时,整个 PHP 进程没有响应,并且任何日志中都没有错误。正好在这一行
$token_response = $client->post($token_url, .......
我在调试会话中运行了这个;并且 URL、Client ID 和 Secret 是通过配置属性正确生成的;我能看到的唯一异常是FileNoFoundException,当它确实找到任何用于节流登录的缓存键时发生,并且这一切都发生在进行此调用并且应用程序继续对用户进行身份验证之前。
当我通过 Postman 或 artisan tinker 使用相同的参数发出这个请求时,我可以得到带有 access_token、refresh_token 和 expires_in 数据的响应。
【问题讨论】:
-
先用 try/catch 块包装你的代码,然后 dd 错误
-
包裹在 try catch 中,我仍然没有看到打印到日志或抛出异常
-
默认情况下,guzzelhttp 会“永远”等待请求的到达。您可以而且应该在客户端选项中设置timeout,以防止等待太久。
-
$client->post(config('app.url').'/oauth/token', [ 'form_params' => [ 'grant_type' => 'password', 'client_id' => config('...), 'client_secret' => config('...'), 'username' => $request->email, 'password' => $request->password, 'scope' => '', ], ],[ 'timeout' => 5, // Response timeout 'connect_timeout' => 5, // Connection timeout ]);这是添加超时的正确方法吗?
标签: php laravel guzzle laravel-passport