X-XSRF-TOKEN 和 X-CSRF-TOKEN 有什么区别? [英] what is the difference between X-XSRF-TOKEN and X-CSRF-TOKEN?

查看:55
本文介绍了X-XSRF-TOKEN 和 X-CSRF-TOKEN 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时使用隐藏字段,何时使用标题以及为什么?
X-XSRF_TOKEN 什么时候使用?
X-CSRF TOKEN我们什么时候使用?

When use hidden field and when use header and why ?
X-XSRF_TOKEN when we use?
X-CSRF TOKEN when we use?

推荐答案

所有这些都是为了跨站点请求伪造保护,并且您只需要使用其中一个即可向后端发送请求.不同的名称来自不同的框架.

All of them are for cross site request forgery protection and you need to use just one of them when sending a request to backend. Different names come from different frameworks.

这一切都是关于向后端发送一个 csrf 值.然后后端会将其与该特定用户的数据库中存储的 csrf 值进行比较,如果匹配,则允许处理请求.

It's all about sending a csrf value to backend. Then backend will compare it with the csrf value stored in database for that specific user and if it matches, it will allow processing the request.

csrf :

  • 用于 html 表单(不是 ajax)
  • 在渲染 html 表单时在后端生成.
  • 我们无法直接在 html 表单中设置请求头,因此一种简单的方法是通过表单输入将其作为隐藏字段发送.
  • 你可以随意命名这个隐藏的输入.例如

x-csrf-token:

  • 它被添加到请求ajax请求的头.
  • 要使用它,我们可以在渲染 html 时将 csrf 值 放在一个元标记中,然后在前端我们可以从该元标记中获取值并将其发送到后端.
  • It is added to the request header for ajax requests.
  • To use it, we can put the csrf value in a meta tag while rendering the html, then in front end we can get the value from that meta tag and send it to backend.

Laravel 特定:

Laravel specific:

  • 使用 laravel 作为后端时.Laravel 会自动检查此标头并将其与数据库中的有效 csrf 值 进行比较.(laravel 有一个中间件)
  • When using laravel as backend. Laravel checks this header automatically and compares it to the valid csrf value in database.(laravel has a middleware for this)

x-xsrf-token:

  • 它被添加到请求ajax请求的头.
  • angular 和 axios 等流行库,会自动从 xsrf-token cookie 中获取此标头的值并将其放入每个请求标头中.
  • 要使用它,我们应该在后端创建一个名为 xsrf-token 的 cookie,然后我们使用 angular 或 axios 的前端框架会自动使用它.
  • It is added to the request header for ajax requests.
  • Popular libraries like angular and axios, automatically get value of this header from xsrf-token cookie and put it in every request header.
  • To use it, we should create a cookie named xsrf-token in backend, then our front end framework that uses angular or axios will use it automatically.

Laravel 特定:

Laravel specific:

  • 因为它很受欢迎,所以 Laravel 在每个响应中都会创建这个 cookie.
  • 所以当你使用 axiosangularlaravel 时,你不需要做任何事情.只需登录用户,'auth' 中间件就可以完成这项工作.
  • 在 laravel 中,与 x-csrf-token 相比,它是一个更大的字符串,因为 cookie 在 laravel 中是加密的.
  • Because it's popular, laravel creates this cookie in each response.
  • so when you're using for example axios or angular with laravel, you don't need to do anything. just log user in and 'auth' middleware will do the job.
  • In laravel, its a bigger string compared to x-csrf-token because cookies are encrypted in laravel.

这篇关于X-XSRF-TOKEN 和 X-CSRF-TOKEN 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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