登录操作后在 Guzzle HTTP 客户端中设置 Authorization Bearer 标头 - Laravel [英] Set the Authorization Bearer header in Guzzle HTTP client After Login Action - Laravel
问题描述
我目前正在处理一个 Laravel 项目,以向 API 发出请求.对端点的每个请求都需要标头中的令牌.
I'm currently working on a laravel project to make a request to the API. Every request to an endpoint requires a token in the header.
我创建了一个用于登录的函数,当登录成功时,我想在对端点的每个请求的标头中放置一个令牌.
I created a function for login, when login is successful I want to put a token in the header for each request to the endpoint.
我可以使用 Guzzle 做到这一点吗?
Can I do that using Guzzle?
这是我的登录功能
public function login(Request $request)
{
$client = new Client();
$url = "http://localhost:8002/login";
$request = $client->post($url, [
'headers'=> ['Content-Type' => 'application/json'],
'body' => json_encode([
'email' => $request->email,
'password' => $request->password,
])
]);
$response = json_decode($request->getBody());
$token = $response->result->token; //I have got the token
}
推荐答案
根据您的情况,您应该使用任何数据存储在成功登录后保留您的授权令牌.会话存储将是一个好的开始.
Depending on your case you should use any data store to keep your authorization token after successful login. Session store would be a good start for that.
此外,根据您的 API 使用的授权类型(不记名令牌、基本身份验证...),向 Guzzle 请求添加标头将如下所示:
Also depending on the type of authorization your API is using(Bearer token, Basic auth...) adding header to the Guzzle request will look like:
$request = $client->post($url, [
'headers'=> ['Authorization' => 'your auth header with auth token'],
'body' => json_encode([
'foo' => 'bar',
])
]);
这篇关于登录操作后在 Guzzle HTTP 客户端中设置 Authorization Bearer 标头 - Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!