Angular2和Laravel CSRF保护 [英] Angular2 and Laravel CSRF protection

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

问题描述

我已经阅读了一些主题

我遇到的问题在于这段代码

And the problem I encountered is lies in this piece of code

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

我使用Angular2作为核心引擎,该引擎将AJAX请求发送到Laravel API,而我没有使用刀片模板-只是 .html文件,所以我无法调用php函数 csrf_token()

I'm using Angular2 as core engine, which sending AJAX requests to Laravel API and I'm not using blade templates - just .html files, so I can't call php function csrf_token() from html file

因此,我通过扩展我的方法添加了一个临时解决方案/var/www/pandacrm/app/Http/Middleware/VerifyCsrfToken.php文件

So, I added a temporary solution by extending my /var/www/pandacrm/app/Http/Middleware/VerifyCsrfToken.php file

public function handle($request, Closure $next)
{
    if ( ! $request->is('api/*'))
    {
        return parent::handle($request, $next);
    }

    return $next($request);
}

但这似乎不是解决问题的最佳方法,还有其他解决方案可以解决此问题吗?

But it seems not the best way to work around, is there any other solutions to resolve this issue?

推荐答案

您可以通过在HTML文件中使用JavaScript,使用 csrf-token 创建 meta 标签!

You can create a meta tag with csrf-token by using JavaScript in your html file!

操作方法:

向Laravel Route发送Ajax请求以获取令牌.(在Controller动作中返回 csrf-token ),然后在您的html文件中创建带有该标记的meta标签.

Send an Ajax request to Laravel Route to get token. (return csrf-token in a Controller action) And then create a meta tag with that token in your html file.

但是在执行此操作之前,您必须在该特定路由上禁用csrf保护.对于laravel5和< > :在href ="https://laravel.com/docs/5.3/csrf#csrf-clusion-uris" rel ="nofollow noreferrer">此处

But before doing this, you have to disable csrf protection on that specific route. There is a way to do this here for laravel5 and here for 5.3.

现在您有了一个带有 csrf 的元标记,该标记可用于其他ajax请求.

Now you have a meta tag with csrf that can be used for other ajax requests.

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

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