API Rails路由中令牌是路由的一部分

huangapple go评论58阅读模式
英文:

API Rails routes where token is part of the route

问题

Sure, here is the translated content you requested:

我需要创建一个Ruby on Rails API,其中路由看起来像这样

mydomain.com/api/v1/xxxxxxxx/
mydomain.com/api/v1/xxxxxxxx/messages
mydomain.com/api/v1/xxxxxxxx/authors/123/books

xxxxxxxx 代表API密钥,应该被提取为params[:key]或类似的params[:api_connection_key]

例如,mydomain.com/api/v1/xxxxxxxx/messages 指向 app/controllers/api/v1/messages_controller.rb

我想知道你会如何设计config/routes.rb来实现这个?(控制器和其余逻辑都没问题,只涉及路由)

不,mydomain.com/api/v1/messages?key=xxxxxxxx 不是一个选项,头部验证也不行。

英文:

I need to create a Ruby on Rails API where routes will look like

mydomain.com/api/v1/xxxxxxxx/
mydomain.com/api/v1/xxxxxxxx/messages
mydomain.com/api/v1/xxxxxxxx/authors/123/books

xxxxxxxx represent the API key and it should be picked up as a params[:key] or something simmillar likeparams[:api_connection_key]

e.g mydomain.com/api/v1/xxxxxxxx/messages point to app/controllers/api/v1/messages_controller.rb

I'm wondering how would you design the config/routes.rb to achive this ? (controllers and rest of logic is fine, just routes)

no mydomain.com/api/v1/messages?key=xxxxxxxx is not an option and Header authentication is out of the question

答案1

得分: 3

scope支持动态段

Rails.application.routes.draw

  namespace :api do
    namespace :v1 do
      scope "/:key" do
        resources :messages
      end
    end
  end
  
end
英文:

scope supports dynamic segments

Rails.application.routes.draw

  namespace :api do
    namespace :v1 do
      scope "/:key" do
        resources :messages
      end
    end
  end
  
end

huangapple
  • 本文由 发表于 2023年5月17日 18:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定