2018年1月4日 星期四

rails csrf token

關於什麼是 CSRF: https://everyday1percent.blogspot.com/2017/12/csrf.html

rails 主要就是這裡

```
def csrf_meta_tags
  if protect_against_forgery?
    [
      tag("meta", name: "csrf-param", content: request_forgery_protection_token),
      tag("meta", name: "csrf-token", content: form_authenticity_token)
    ].join("\n").html_safe
  end
end
```

所以前端要用的話就要在 Header 送 X-CSRF-Token 這個參數

https://stephenhowells.net/rails-5-user-registration-with-devise-vue-js-and-axios/

這裡有簡單的用法(前端使用 Axois)

後來搭配 gon 實作成:

```js
import axios from 'axios'

const create = (baseURL = 'http://localhost:3000/') => {
  const api = axios.create({
    // baseURL,
    headers: {
      'Cache-Control': 'no-cache',
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-Token': gon.general.rails.csrf.token
    },
    timeout: 10000
  })

  const cancel = ({ market, id }) => api.delete(`/exchange/markets/${market}/orders/${id}`)

  return {
    cancel
  }
}

export default {
  create
}

```


https://medium.com/rubyinside/a-deep-dive-into-csrf-protection-in-rails-19fa0a42c0ef


沒有留言:

張貼留言