Angular2和Laravel CSRF保护

编程入门 行业动态 更新时间:2024-10-26 14:34:08
本文介绍了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 ="laravel/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保护

本文发布于:2023-11-01 17:37:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Laravel   CSRF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!