【问题标题】:Provide csrf _token in headers when using Laravel API使用 Laravel API 时在 headers 中提供 csrf _token
【发布时间】:2022-10-14 04:05:21
【问题描述】:

在使用我的 api 时,如何创建一个 Laravel Gate,其中客户端必须在标头中提供 CSRF 令牌?

想法是在使用我的路线时我想要某种门: http://127.0.0.1:50004/api/third-party/unsplash

否则,任何人都可以复制和使用上述路线。

api.php

Route::get('/third-party/unsplash', [UnsplashController::class, 'show'])
    **// my gate here!!!!**

UnsplashController.php

 public function show()
    {
        return ['authorizationKey' => 'Client-ID 1234'];
    }

Unsplash.vue 文件:

const myAsync = async function fetchUnsplash() {
  const myAPIKey = await fetch(
    'http://127.0.0.1:50004/api/third-party/unsplash'
  );

  const dataMyAPIKey = await myAPIKey.json();

  const response = await fetch('https://api.unsplash.com', {
    headers: {
      Authorization: dataMyAPIKey,
    },
  });

  console.log(response);
};

【问题讨论】:

  • 你想保护你的 api 路由吗?
  • 是的。我想保护我的 api 路由。

标签: laravel api vue.js


【解决方案1】:

您可能希望使用Laravel Sanctum 之类的完整 API 身份验证,而不是依赖 CSRF 令牌。实施 Sanctum 将帮助您有效地保护您的 API(包括from CSRF attacks)。

如果你真的想要在标头中要求 CSRF 令牌,您可以通过将自定义 middleware 添加到那些将检查 CSRF 令牌的路由来实现。您可以查看VerifyCsrfToken 中间件作为起点。通常,X-CSRF-TOKEN 标头用于在请求中传递 CSRF 令牌。

最后,如果您选择将/third-party/unsplash 路由从GET 转换为POST,您可能只使用内置的VerifyCsrfToken 中间件。

总而言之,我认为使用像 Sanctum 这样更强大的解决方案将为您提供良好的服务,并防止您可能尚未想到的其他潜在问题。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2014-04-15
    • 2015-05-20
    • 2013-06-02
    • 2015-01-01
    • 2019-11-12
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多