Ruby-on-rails 在 rails 中进行 Http 基本身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14374580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Doing a Http basic authentication in rails
提问by sriram
Hi I'm from Grails background and new to Rails. I wish to do http basic authentication in rails.
嗨,我来自 Grails 背景,并且是 Rails 新手。我希望在 Rails 中进行 http 基本身份验证。
I have a code in grails which does basic authentication like this:
我在 grails 中有一个代码,它执行这样的基本身份验证:
def authString = "${key}:".getBytes().encodeBase64().toString()
def conn = "http://something.net".toURL().openConnection()
conn.setRequestProperty("Authorization", "Basic ${authString}")
Is it the same can be done with rails?
用rails也能做到吗?
Thanks in advance.
提前致谢。
回答by Nishant
Write the below code, in the controller which you want to restrict using http basic authentication
在要使用 http 基本身份验证限制的控制器中编写以下代码
class ApplicationController < ActionController::Base
http_basic_authenticate_with :name => "user", :password => "password"
end
Making a request with open-uri would look like this:
使用 open-uri 发出请求将如下所示:
require 'open-uri'
open("http://www.your-website.net/",
http_basic_authentication: ["user", "password"])
回答by sergserg
In Ruby on Rails 4 you can easily apply basic HTTP Authentication site wide or per controller depending on the context.
在 Ruby on Rails 4 中,您可以根据上下文轻松地在站点范围内或每个控制器上应用基本的 HTTP 身份验证。
For example, if you need site wide authentication:
例如,如果您需要站点范围的身份验证:
class ApplicationController < ActionController::Base
http_basic_authenticate_with name: "admin", password: "hunter2"
end
Or on a per controller basis:
或者在每个控制器的基础上:
class CarsController < ApplicationController
http_basic_authenticate_with name: "admin", password: "hunter2"
end
回答by Kyle Carlson
I upvoted @Nishant's answer but wanted to add another tidbit. You can always set filters so it only applies to certain controller actions by passing onlyor exceptlike so:
我赞成@Nishant 的回答,但想添加另一个花絮。您始终可以设置过滤器,使其仅通过传递only或except类似的方式应用于某些控制器操作:
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", only: [:admin, :new, :edit, :destroy]
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", only: [:admin, :new, :edit, :destroy]
or
或者
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", except: [:show]
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", except: [:show]
Very helpful in many instances.
在许多情况下非常有帮助。
回答by heriberto perez
# app/controllers/application_controller.rb
before_filter :http_basic_auth
def http_basic_auth
if ENV['HTTP_AUTH'] =~ %r{(.+)\:(.+)}
unless authenticate_with_http_basic { |user, password| user == && password == }
request_http_basic_authentication
end
end
end
and then you just need to export your environment variable with the user:password for example:
然后您只需要使用 user:password 导出您的环境变量,例如:
export HTTP_AUTH=user:pass
if you are using heroku.com:
如果您使用的是 heroku.com:
heroku config:set HTTP_AUTH=user:pass
回答by Oto Brglez
When connecting to HTTP endpoints protected by basic HTTP authentication I usually use HTTParty. HTTPartyis simple wrapper for lower Ruby STD classes like net/http.
当连接到受基本 HTTP 身份验证保护的 HTTP 端点时,我通常使用HTTParty。HTTParty是低级 Ruby STD 类(如net/http)的简单包装器。
Example usage of HTTPartywith basic auth.
HTTParty与基本身份验证的示例用法。
class Delicious
include HTTParty
base_uri 'https://api.del.icio.us/v1'
def initialize(u, p)
@auth = {username: u, password: p}
end
def recent options={}
options.merge!({basic_auth: @auth})
self.class.get('/posts/recent', options)
end
end
delicious = Delicious.new("<username>", "<password>")
pp delicious.recent #=> list of recent elements
Check for more examples on GitHub.
在 GitHub 上查看更多示例。
回答by My God
For the latest rails version there is a ASCIIcastthat explains with steps the HTTP Basic Authentication.
对于最新的 rails 版本,有一个ASCIIcast解释HTTP 基本身份验证的步骤。
The link goes here.
链接在这里。
Side Note:Be warned that HTTP Basic Authentication transmits the username and password in clear text, so you should not use this method for applications where a higher level of security is required.
旁注:请注意,HTTP 基本身份验证以明文形式传输用户名和密码,因此对于需要更高级别安全性的应用程序,不应使用此方法。
回答by Kansha
There is a great Rails Cast on this topic
关于这个主题有一个很棒的 Rails Cast
回答by dowi
Above answers are correct, but it is better to not put the user and password in the source code.
以上答案是正确的,但最好不要在源代码中输入用户和密码。
Better have the password in environment variables for production (in the code is OK for development)
最好在环境变量中有密码用于生产(代码中可以用于开发)
class YourController..
http_basic_authenticate_with name: ENV["HTTP_BASIC_AUTH_USER"], password: ENV["HTTP_BASIC_AUTH_PASSWORD"], if: -> { ENV['RAILS_ENV'] == 'production' }
http_basic_authenticate_with name: "user", password: "pass", if: -> { ENV['RAILS_ENV'] != 'production' }

