如何在自定义控制器操作中添加HTTP AUTH?
class MyController < ApplicationController
def index
#NO AUTH
end
def custom
#I NEED HTTP AUTH ONLY HERE
end
end
routes.rb中:
get 'my/custom', to: 'my#custom'
class MyController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", only: [:custom]
def custom
#I NEED HTTP AUTH ONLY HERE
end
end
您还可以直接在操作中调用auth:
class MyController < ApplicationController
def custom
authenticate_or_request_with_http_basic do |username, password|
username == "dhh" && password == "secret"
end
...
end
end
以下是更高级用法的文档:https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
您可以使用http_basic_authenticate_with方法。我已将:custom符号传递给:only选项,这意味着身份验证仅适用于该方法。
class MyController < ApplicationController
http_basic_authenticate_with name: "username", password: "password", only: :custom
def index
#NO AUTH
end
def custom
#I NEED HTTP AUTH ONLY HERE
end
end