2017-09-26 63 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

相關問題