【发布时间】:2018-03-09 04:14:03
【问题描述】:
首先,Laravel 的身份验证配置为用户指定了基于令牌的身份验证方法:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
我有几个要保护的 ajax 端点,因此我的应用程序之外的任何人都无法与它们交互。我看过 Passport,但考虑到这个身份验证配置,我似乎实际上不需要它。 如何使用此令牌来保护我的 ajax 端点,并在可能的情况下识别请求所属的用户?
目前我的 api.php 路由文件看起来像:
//Route::middleware('auth:api')->group(function () {
Route::post('subscribe', 'SubscriptionController@create');
Route::post('unsubscribe', 'SubscriptionController@delete');
//});
我认为 Laravel 可能已经为 VueJS 实现处理了 auth 或其他东西,但它看起来不像。我的 ajax 请求如下所示:
this.$http.post('/api/subscribe', {
subscribed_by: currentUser,
game_id: this.gameId,
guild_discord_id: this.guildDiscordId,
channel_id: newChannelId,
interests: this.interests.split(',')
}).then(response => {
// success
}, response => {
console.error('Failed to subscribe');
});
【问题讨论】:
-
看看JWTAuth是否有帮助!!
-
否则,您应该在用户表
api_token中创建一个包含 60 个字符的随机值的列,然后您需要在您的调用中传递它auth()->user()->api_token并检查您是否收到数据库中的令牌。 -
我打算将它用于 ajax 请求,因此静态令牌不起作用。