2017-09-26 66 views
1

我有一个Laravel 5.5应用程序(不使用Passport),我试图从我使用库存基础结构构建的VueJS组件访问/api路由。使用vue-resource我无法获得有效的,经过验证的回复。我可以看到XSRF令牌传递在这里:Laravel基本身份验证:api 401未授权

enter image description here

我VueJS:

methods: { 
     updateSubscription(newChannelId, oldChannelId) { 
      if (oldChannelId < 1 && newChannelId > 0) { 
       console.log('new subscription', this); 
       this.$http.post('/api/subscribe', { 
        'game_id': this.gameId, 
        'channel_id': newChannelId 
       }).then(response => { 
        // success 
       }, response => { 
        console.error('Failed to subscribe'); 
       }); 

我Laravel路线routes/api.php

Route::middleware('auth:api')->group(function() { 
    Route::post('subscribe', '[email protected]'); 
    Route::post('unsubscribe', '[email protected]'); 
    Route::post('update-subscription', '[email protected]'); 
}); 

我想Laravel处理XSRF出来的大门,我不会遇到这个问题。我想我不熟悉auth:api 100%给我的HTTP内核的样子:

protected $middlewareGroups = [ 
    'web' => [ 
     \App\Http\Middleware\EncryptCookies::class, 
     \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, 
     \Illuminate\Session\Middleware\StartSession::class, 
     // \Illuminate\Session\Middleware\AuthenticateSession::class, 
     \Illuminate\View\Middleware\ShareErrorsFromSession::class, 
     \App\Http\Middleware\VerifyCsrfToken::class, 
     \Illuminate\Routing\Middleware\SubstituteBindings::class, 
    ], 

    'api' => [ 
     'throttle:60,1', 
     'bindings', 
    ], 
]; 

/** 
* The application's route middleware. 
* 
* These middleware may be assigned to groups or used individually. 
* 
* @var array 
*/ 
protected $routeMiddleware = [ 
    'auth'  => \Illuminate\Auth\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 
    'can'  => \Illuminate\Auth\Middleware\Authorize::class, 
    'guest'  => \App\Http\Middleware\RedirectIfAuthenticated::class, 
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 
]; 

我错过了什么?

回答

0

我不认为你的401错误与CSRF令牌有关。您已将auth:api中间件添加到您的路由中,因此需要为每个请求传递一个有效的API令牌来验证请求。我看不到你在做这个。

退房的TokenGuard类,看看它是如何工作的内部:https://github.com/laravel/framework/blob/5.5/src/Illuminate/Auth/TokenGuard.php

基本上,你需要传递称为api_token请求参数或Authorization头Authorization: Bearer <api_token>每个请求。

+0

这很有道理......但Laravel是否具备验证API的功能,还是需要使用“Passport”来管理这个功能? – Webnet

+0

如果你愿意,你可以在你的用户表中添加一个'api_token'字段。这需要以纯文本的形式存储以便进行比较,所以不是最安全的,但它很快就可以正常工作。 – fubar

+0

在这种情况下,它只是一个Ajax请求。我想我应该删除'auth:api'令牌,并且只是要求用户登录才能发出这个请求。无论如何通过查看源代码可见,在JS中添加令牌是没有意义的。 – Webnet

相关问题