簡體   English   中英

當使用JavaScript使用API​​時,對/ api路由禁用Laravel CSRF保護

[英]Disable Laravel CSRF Protection for /api routes when consuming API with JavaScript

我有一個Laravel后端和React前端。 為了進行開發,React在localhost:3000上運行,而Laravel在localhost:8080 ,所以我不得不允許Cors。

我已經成功設置了Passport,並且能夠使用JavaScript使用我的API

但是,對於每個請求,我都必須包括X-CSRF-TOKEN才能訪問受保護的API路由,該路由有效,但是為了進行開發,我想禁用API的CSRF-Protection。

我已經嘗試將/api路由添加到VerifyCsrfTokenexcept數組,並從Kernel.php刪除了中間件,但這似乎並沒有改變我仍然需要發送CSRF-Token的事實。

我正在使用Laravel 5.8,並使用JavaScript提取來發出請求。

VerifyCsrfToken:

protected $except = [
    '/api/*'
];```

我在內核中注釋掉了VerifyCsrfToken:

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,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

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

API路由示例:

Route::get('test', function() {
    return response()->json(['success' => 'Hello!']);
})->middleware('auth:api');

我如何嘗試訪問API:

const checkStatus = (response) => {
    console.log(response);
    if (response.ok) {
        return response;
    } else {
        const error = new Error(response.statusText);
        error.response = response;
        throw error;
    }
}

const parseJSON = res => res.text();

const Fetcher = {
    get: (ressource) => {
        return fetch(CONSTANTS.API_URL + ressource, {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                //'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            credentials: 'include'
        })
            .then(checkStatus)
            .then(parseJSON)
    },
    post: (ressource, data) => {
        return fetch(CONSTANTS.API_URL + ressource, {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                //'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            credentials: 'include',
            body: data
        })
            .then(checkStatus)
            .then(parseJSON)
    }
}

嘗試找出問題所在。
刪除路由中的auth:api中間件:

Route::get('api/test', function() {
    return response()->json(['success' => 'Hello!']);
});

請注意,URL是“ api / test”,而不僅僅是“ test”,因為您定義了$ except數組,如下所示:

protected $except = [
    '/api/*'
];

不通過CSRF令牌即可撥打電話。

已編輯

從有關auth:api中間件的laravel文檔中:

Laravel包含一個身份驗證保護,它將自動驗證傳入請求上的API令牌。 您只需要在需要有效訪問令牌的任何路由上指定auth:api中間件:

這意味着您必須將API令牌傳遞給auth:api中間件下的路由,否則會出現401錯誤。

在路由文件夾下處理您在api.php中而不是在web.php中的api路由

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM