Laravel API TokenMismatchException [英] Laravel API TokenMismatchException

查看:24
本文介绍了Laravel API TokenMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有发布数据的 API 调用;假设这是登录过程.

I have an API call with post data; let's say this is the login process.

使用 Chrome 的 Postman 扩展程序,我通过 POST 发送用户名和密码以登录用户.但我收到了这条消息:

With the Postman extension of Chrome I send, via POST, the username and password to log the user in. But I got this message:

Illuminate \ Session \ TokenMismatchException

在我的基本控制器中,我有:

In my Base Controller I have:

    /**
     * Initializer.
     *
     * @return void
     */
    public function __construct() {
        // CSRF Protection
        $this->beforeFilter('csrf', array('on' => 'post'));

        // Layouts/Notifications
        $this->messageBag = new Illuminate\Support\MessageBag;

    }

当我使用 beforeFilter 删除行时,一切正常.但这不能成为解决方案.任何 POST 调用都会收到此错误消息.我知道我需要这个 _token.但是当我从 API 调用时如何获得这个令牌?我知道我可以在 Laravel 内部创建一个令牌,但是当我通过 API 从外部调用时我该怎么做?

When I delete the row with the beforeFilter everything works fine. But this cannot be a solution. Any POST call would get this error message. I KNOW that I need this _token. But how I get this token when I call from the API? I know that I can create a token inside Laravel, but how can I do this when I call from outside via API?

推荐答案

通常 API 用于跨站点请求.所以你的 CSRF 保护是没有意义的.

Generally API's are used for cross site requests. So your CSRF protection is pointless.

如果您不打算跨站点使用它,那么 API 可能不是您要尝试执行的操作的最佳解决方案.无论如何,您可以创建一个返回令牌的 API 端点.

If you're not gonna use it cross-site, chances are that an API is not the optimal solution for what you're trying to do. Anyway, you could make an API endpoint which returns a token.

public function getToken(){
    return Response::json(['token'=>csrf_token()]);
}

如果您想在某些方法上禁用 CSRF 保护,您可以使用 exceptonly.

If you want to disable CSRF-protection on some methods, you could use except or only.

$this->beforeFilter('csrf', array('on' => 'post', 
                                 'except'=>array('methodName', 'anotherMethod')
                                  ));

请参阅 官方 Laravel 文档.

这篇关于Laravel API TokenMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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