Laravel X-CSRF-Token 与 POSTMAN 不匹配 [英] Laravel X-CSRF-Token mismatch with POSTMAN

查看:38
本文介绍了Laravel X-CSRF-Token 与 POSTMAN 不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试与我使用 Laravel 构建的 REST API 对话.但是由于令牌不匹配,与 POSTMAN 的调用被拒绝.我想我需要在标头中包含 CSRF 令牌.但是我需要加密的吗?当我插入这个令牌时,我仍然收到令牌不匹配的错误.

I try to talk to my REST API built with Laravel. But the call with POSTMAN is rejected due to a token mismatch. I guess I need to include the CSRF token in the header. But do I need the encrypted one? When I insert this token I still get the error that there is a token mismatch.

我使用以下方法检索我的令牌:

I retrieve my token by using:

$encrypter = app('Illuminate\Encryption\Encrypter');
$encrypted_token = $encrypter->encrypt(csrf_token());
return $encrypted_token;

但这应该在每次刷新时改变吗?

but is this supposed to change on every refresh?

推荐答案

如果您不使用表单 - 例如 API - 您可以按照此处的步骤操作 https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0:

If you aren't using forms - for an API for example - you can follow the steps here https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0:

基本上,将以下内容添加到您的刀片或树枝标题

Essentially, add the following to your blade or twig header

<meta name="csrf-token" content="{{ csrf_token() }}">

如果尚未安装 Postman Interceptor,请安装并打开它

Install Postman Interceptor if not already installed, and turn it on

然后,在您的浏览器中登录该站点(您需要获得授权),然后检查元素或查看源以检索令牌

Then, in your browser log into the site (you need to be authorised), and either inspect element or view source to retrieve the token

在 Postman 中,根据需要设置 GET/POST 等,并在您的标题中创建一个新对

In Postman, set GET/POST etc as needed, and in your header create a new pair

X-CSRF-TOKEN        tokenvaluetobeinserted235kwgeiOIulgsk

有些人建议在测试 API 时关闭 CSRF 令牌,但实际上您并不是在测试它.

Some people recommend turning off the CSRF token when testing the API, but then you aren't really testing it are you.

如果您确实发现仍然有错误,请使用 preview 检查响应,因为 Laravel 的错误消息往往相当明确.如果没有返回,请检查您的 php_error.log(无论它叫什么).

If you do find you still have errors, check the response back using preview as Laravel tends to be fairly explicit with their error messages. If nothing is coming back, check your php_error.log (what ever it is called).

ps 2018 年 10 月 - 我现在使用 Laravel Passport 来处理 API 注册、登录和用户令牌 - 值得一看!

ps Oct 2018 - I now user Laravel Passport for handling API registration, logins and user tokens - worth a look!

这篇关于Laravel X-CSRF-Token 与 POSTMAN 不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆