首页 > 解决方案 > Rails 路由:如何创建不可猜测的路由

问题描述

我需要以某种方式使我的路线不可猜测。

实际上,用户通过读取二维码发出获取请求来完成操作周期(订单状态为完成)。

但是很容易“猜测”路线,因为 id 在整个订单生命周期中是相同的。当状态被接受时(完成前),用户可以在 URL 中看到 id。

所以我想在 url 中添加一种随机令牌,这样他们就无法猜测路线......

我的路线是这样的ATM:

resources :orders, only: %i(create show index destroy edit update) do
    resources :reviews, only: %i(create new show index)
    resources :payments, only: %i(new create)
    member do
      post 'accept'
    end
    member do
      get 'read_qrcode'
    end
  end

这会生成此模式到 read_qrcode 路由:

/orders/:id/read_qrcode

所以我想在 read_qrcode 之后添加任何类型的令牌,可能是 MD5 哈希、时间戳或其他任何内容,并获得这样的 url:

/orders/:id/read_qrcode/1a79a4d60de6718e8e5b326e338ae533

我怎样才能达到这个结果,或者可能是另一种解决方案?

标签: ruby-on-railsdeviseurl-routing

解决方案


Rails 6.1 也支持签名的 id

order = Order.find(1)

Order.find_signed(order.signed_id)

https://github.com/rails/rails/pull/39313

https://blog.saeloun.com/2020/05/20/rails-6-1-adds-support-for-signed-ids-to-active-record.html


推荐阅读