Rails: 如何在自定义操作中添加 HTTP AUTH
Rails: How to add HTTP AUTH at custom action
如何在自定义控制器操作中添加 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
也可以直接在action中调用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
如何在自定义控制器操作中添加 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
也可以直接在action中调用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