我正在为 Laravel 构建一个 API,我想在标头中发送
api_token
而不是表单帖子。这是已经内置的东西还是我必须弄清楚如何创建自己的身份验证驱动程序?
在我自己对此进行了一些努力之后,我成功了。 您需要首先遵循这个小教程,了解如何在 Laravel API 中使用 api_token: https://gistlog.co/JacobBennett/090369fbab0b31130b51
然后,一旦您在用户表等中拥有 api_token,您现在就可以在每个请求的标头中传递它。
我的 laravel 使用的是 Vueify 模板,即我在 /components/Comment.vue 等文件下。
第一步是通过刀片模板中的组件定义传递属性,将用户 api_token 传递到 Vue 模板:
<comments id_token="{{ access()->user()->api_token }}"></comments>
然后确保在您的 .vue 文件中通过将其添加到“props”来接受该属性:
export default {
data: function() {
return {
edit: false,
list: [],
comment: {
id: '',
name: '',
body: ''
}
};
},
props: ['id_token'],
created: function() {
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
this.fetchCommentList();
},
请注意,上面我还将令牌添加到公共标头中,以便让它遍历所有方法中使用的每个请求。
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
如果您正在使用 API,则无需创建身份验证驱动程序,只需向 API 端点发出请求。选择您喜欢的方法,然后提出请求,不要像在网页上使用身份验证驱动程序时那样想。
这是如何通过标头发送 $token 的示例。使用 cURL 和 Guzzle
$data = [
'value1' => 'value1',
'value2' => 'value2'
];
使用卷曲
$headers = [
'Authorization: Bearer '.$token
];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://api.domain.com/endpoint');
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch2);
curl_close ($ch2);
带Guzzle
$headers = [
'Authorization' => 'Bearer '.$token
];
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'http://api.domain.com/endpoint',[
'form_params' => $data,
'headers' => $headers,
]);
我希望这有帮助!