1 module ActionController
2 module HttpAuthentication
3 # Makes it dead easy to do HTTP Basic authentication.
5 # Simple Basic example:
7 # class PostsController < ApplicationController
8 # USER_NAME, PASSWORD = "dhh", "secret"
10 # before_filter :authenticate, :except => [ :index ]
13 # render :text => "Everyone can see me!"
17 # render :text => "I'm only accessible if you know the password"
22 # authenticate_or_request_with_http_basic do |user_name, password|
23 # user_name == USER_NAME && password == PASSWORD
29 # Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
30 # the regular HTML interface is protected by a session approach:
32 # class ApplicationController < ActionController::Base
33 # before_filter :set_account, :authenticate
37 # @account = Account.find_by_url_name(request.subdomains.first)
42 # when Mime::XML, Mime::ATOM
43 # if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
44 # @current_user = user
46 # request_http_basic_authentication
49 # if session_authenticated?
50 # @current_user = @account.users.find(session[:authenticated][:user_id])
52 # redirect_to(login_url) and return false
58 # In your integration tests, you can do something like this:
60 # def test_access_granted_from_xml
62 # "/notes/1.xml", nil,
63 # :authorization => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
66 # assert_equal 200, status
69 # Simple Digest example:
71 # require 'digest/md5'
72 # class PostsController < ApplicationController
73 # REALM = "SuperSecret"
74 # USERS = {"dhh" => "secret", #plain text password
75 # "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
77 # before_filter :authenticate, :except => [:index]
80 # render :text => "Everyone can see me!"
84 # render :text => "I'm only accessible if you know the password"
89 # authenticate_or_request_with_http_digest(REALM) do |username|
95 # NOTE: The +authenticate_or_request_with_http_digest+ block must return the user's password or the ha1 digest hash so the framework can appropriately
96 # hash to check the user's credentials. Returning +nil+ will cause authentication to fail.
97 # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
98 # the password file or database is compromised, the attacker would be able to use the ha1 hash to
99 # authenticate as the user at this +realm+, but would not have the user's password to try using at
102 # On shared hosts, Apache sometimes doesn't pass authentication headers to
103 # FCGI instances. If your environment matches this description and you cannot
104 # authenticate, try this rule in your Apache setup:
106 # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
110 module ControllerMethods
111 def authenticate_or_request_with_http_basic(realm
= "Application", &login_procedure
)
112 authenticate_with_http_basic(&login_procedure
) || request_http_basic_authentication(realm
)
115 def authenticate_with_http_basic(&login_procedure
)
116 HttpAuthentication
::Basic.authenticate(self, &login_procedure
)
119 def request_http_basic_authentication(realm
= "Application")
120 HttpAuthentication
::Basic.authentication_request(self, realm
)
124 def authenticate(controller
, &login_procedure
)
125 unless authorization(controller
.request
).blank
?
126 login_procedure
.call(*user_name_and_password(controller
.request
))
130 def user_name_and_password(request
)
131 decode_credentials(request
).split(/:/, 2)
134 def authorization(request
)
135 request
.env['HTTP_AUTHORIZATION'] ||
136 request
.env['X-HTTP_AUTHORIZATION'] ||
137 request
.env['X_HTTP_AUTHORIZATION'] ||
138 request
.env['REDIRECT_X_HTTP_AUTHORIZATION']
141 def decode_credentials(request
)
142 ActiveSupport
::Base64.decode64(authorization(request
).split
.last
|| '')
145 def encode_credentials(user_name
, password
)
146 "Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
149 def authentication_request(controller, realm)
150 controller.headers["WWW-Authenticate
"] = %(Basic realm="#{realm.gsub(/"/, "")}")
151 controller
.__send__
:render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized
158 module ControllerMethods
159 def authenticate_or_request_with_http_digest(realm
= "Application", &password_procedure
)
160 authenticate_with_http_digest(realm
, &password_procedure
) || request_http_digest_authentication(realm
)
163 # Authenticate with HTTP Digest, returns true or false
164 def authenticate_with_http_digest(realm
= "Application", &password_procedure
)
165 HttpAuthentication
::Digest.authenticate(self, realm
, &password_procedure
)
168 # Render output including the HTTP Digest authentication header
169 def request_http_digest_authentication(realm
= "Application", message
= nil)
170 HttpAuthentication
::Digest.authentication_request(self, realm
, message
)
174 # Returns false on a valid response, true otherwise
175 def authenticate(controller
, realm
, &password_procedure
)
176 authorization(controller
.request
) && validate_digest_response(controller
.request
, realm
, &password_procedure
)
179 def authorization(request
)
180 request
.env['HTTP_AUTHORIZATION'] ||
181 request
.env['X-HTTP_AUTHORIZATION'] ||
182 request
.env['X_HTTP_AUTHORIZATION'] ||
183 request
.env['REDIRECT_X_HTTP_AUTHORIZATION']
186 # Raises error unless the request credentials response value matches the expected value.
187 # First try the password as a ha1 digest password. If this fails, then try it as a plain
189 def validate_digest_response(request
, realm
, &password_procedure
)
190 credentials
= decode_credentials_header(request
)
191 valid_nonce
= validate_nonce(request
, credentials
[:nonce])
193 if valid_nonce
&& realm
== credentials
[:realm] && opaque
== credentials
[:opaque]
194 password
= password_procedure
.call(credentials
[:username])
196 [true, false].any
? do |password_is_ha1
|
197 expected
= expected_response(request
.env['REQUEST_METHOD'], request
.env['REQUEST_URI'], credentials
, password
, password_is_ha1
)
198 expected
== credentials
[:response]
203 # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
204 # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
205 # of a plain-text password.
206 def expected_response(http_method
, uri
, credentials
, password
, password_is_ha1
=true)
207 ha1
= password_is_ha1
? password
: ha1(credentials
, password
)
208 ha2
= ::Digest::MD5.hexdigest([http_method
.to_s
.upcase
, uri
].join(':'))
209 ::Digest::MD5.hexdigest([ha1
, credentials
[:nonce], credentials
[:nc], credentials
[:cnonce], credentials
[:qop], ha2
].join(':'))
212 def ha1(credentials
, password
)
213 ::Digest::MD5.hexdigest([credentials
[:username], credentials
[:realm], password
].join(':'))
216 def encode_credentials(http_method
, credentials
, password
, password_is_ha1
)
217 credentials
[:response] = expected_response(http_method
, credentials
[:uri], credentials
, password
, password_is_ha1
)
218 "Digest " + credentials
.sort_by
{|x
| x
[0].to_s
}.inject([]) {|a
, v
| a
<< "#{v[0]}='#{v[1]}'" }.join(', ')
221 def decode_credentials_header(request
)
222 decode_credentials(authorization(request
))
225 def decode_credentials(header
)
226 header
.to_s
.gsub(/^Digest\s+/,'').split(',').inject({}) do |hash
, pair
|
227 key
, value
= pair
.split('=', 2)
228 hash
[key
.strip
.to_sym
] = value
.to_s
.gsub(/^"|"$/,'').gsub(/'/, '')
233 def authentication_header(controller
, realm
)
234 controller
.headers
["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
237 def authentication_request(controller
, realm
, message
= nil)
238 message
||= "HTTP Digest: Access denied.\n"
239 authentication_header(controller
, realm
)
240 controller
.__send__
:render, :text => message
, :status => :unauthorized
243 # Uses an MD5 digest based on time to generate a value to be used only once.
245 # A server-specified data string which should be uniquely generated each time a 401 response is made.
246 # It is recommended that this string be base64 or hexadecimal data.
247 # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
249 # The contents of the nonce are implementation dependent.
250 # The quality of the implementation depends on a good choice.
251 # A nonce might, for example, be constructed as the base 64 encoding of
253 # => time-stamp H(time-stamp ":" ETag ":" private-key)
255 # where time-stamp is a server-generated time or other non-repeating value,
256 # ETag is the value of the HTTP ETag header associated with the requested entity,
257 # and private-key is data known only to the server.
258 # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
259 # reject the request if it did not match the nonce from that header or
260 # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
261 # The inclusion of the ETag prevents a replay request for an updated version of the resource.
262 # (Note: including the IP address of the client in the nonce would appear to offer the server the ability
263 # to limit the reuse of the nonce to the same client that originally got it.
264 # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
265 # Also, IP address spoofing is not that hard.)
267 # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
268 # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
269 # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
272 # The nonce is opaque to the client. Composed of Time, and hash of Time with secret
273 # key from the Rails session secret generated upon creation of project. Ensures
274 # the time cannot be modifed by client.
275 def nonce(time
= Time
.now
)
277 hashed
= [t
, secret_key
]
278 digest
= ::Digest::MD5.hexdigest(hashed
.join(":"))
279 Base64
.encode64("#{t}:#{digest}").gsub("\n", '')
282 # Might want a shorter timeout depending on whether the request
283 # is a PUT or POST, and if client is browser or web service.
284 # Can be much shorter if the Stale directive is implemented. This would
285 # allow a user to use new nonce without prompting user again for their
286 # username and password.
287 def validate_nonce(request
, value
, seconds_to_timeout
=5*60)
288 t
= Base64
.decode64(value
).split(":").first
.to_i
289 nonce(t
) == value
&& (t
- Time
.now
.to_i
).abs
<= seconds_to_timeout
292 # Opaque based on random generation - but changing each request?
294 ::Digest::MD5.hexdigest(secret_key
)
297 # Set in /initializers/session_store.rb, and loaded even if sessions are not in use.
299 ActionController
::Base.session_options
[:secret]