gpt4 book ai didi

php - 使用 axios 的 API 请求总是未经 Laravel API 授权

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:15 24 4
gpt4 key购买 nike

我正在使用 Laravel 进行个人项目5.6 和 Axios库(标准 Laravel 5.6 包)。

我需要先发送 GET,然后使用 Laravel 的 API 和 axios 的 http 请求发送 POST 请求,但我没有使用 Passport 或任何类似的库,因为它是一个内部 API,仅服务于 VueJS 从数据库中获取内容。

如果我使用 auth:api 中间件设置我的 API 路由,我总是会得到未经授权的响应,以请求类型为准,这是错误输出:

Error: Request failed with status code 401

消息:

message: "Unauthenticated."

但是,正如我在文档中所读到的,axios header 设置在 laravel 的 bootstrap.js 中以从元标记中读取授权 token (并且代码在那里):

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// further down the file...
let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

虽然,如果需要,这里是 http 请求代码:

axios.post('/api/latest', formData)

那么,如果设置了这些,为什么我未通过身份验证?

我已经尝试删除 auth:api 中间件,当然,它可以正常工作:

- Route::middleware('auth:api')->get('/latest', 'InternalApiController@latestEp');
+ Route::get('/latest', 'InternalApiController@latestEp');

我做错了什么?

最佳答案

I'm not using Passort or any library like that since it's an internal API serving only VueJS to obtain stuff from the database.

如果 API 不是无状态的,这意味着已知用户使用标准 session cookie 登录,那么您可以为 API 路由使用默认的 'web' 中间件。

在默认的 RouteServiceProvider 中,更改 mapApiRoutes 函数以改为使用 web 中间件:

protected function mapApiRoutes()
{
Route::prefix('api')
// ->middleware('api')
->middleware('web')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}

话虽如此,您真的应该将 API 路由放在默认的 'auth' 中间件后面,因为默认情况下它们不受限制。

routes/api.php 文件中:

Route::group(['middleware' => 'auth'], function() {
Route::get('/latest', 'InternalApiController@latest');
});

如果您想确保它是一个 AJAX 请求,您可以创建一个简单的中间件来检查该请求是否将 X-Requested-With header 设置为 XMLHttpRequest .

class RequestIsAjax
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->ajax()) {
return redirect()->route('login.index');
}

return $next($request);
}
}

并将其注册到 \App\Http\Kernel 类的 $routeMiddleware 数组中。

protected $routeMiddleware = [
'ajax' => \App\Http\Middleware\RequestIsAjax::class,

关于php - 使用 axios 的 API 请求总是未经 Laravel API 授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49884611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com