~ubuntu-branches/ubuntu/raring/ruby-actionpack-3.2/raring

« back to all changes in this revision

Viewing changes to lib/action_controller/metal/http_authentication.rb

  • Committer: Package Import Robot
  • Author(s): Ondřej Surý
  • Date: 2012-04-25 09:14:01 UTC
  • Revision ID: package-import@ubuntu.com-20120425091401-3nkf83btcemhjquo
Tags: upstream-3.2.3
Import upstream version 3.2.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
require 'active_support/base64'
 
2
require 'active_support/core_ext/object/blank'
 
3
 
 
4
module ActionController
 
5
  module HttpAuthentication
 
6
    # Makes it dead easy to do HTTP \Basic and \Digest authentication.
 
7
    #
 
8
    # === Simple \Basic example
 
9
    #
 
10
    #   class PostsController < ApplicationController
 
11
    #     http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
 
12
    #
 
13
    #     def index
 
14
    #       render :text => "Everyone can see me!"
 
15
    #     end
 
16
    #
 
17
    #     def edit
 
18
    #       render :text => "I'm only accessible if you know the password"
 
19
    #     end
 
20
    #  end
 
21
    #
 
22
    # === Advanced \Basic example
 
23
    #
 
24
    # Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
 
25
    # the regular HTML interface is protected by a session approach:
 
26
    #
 
27
    #   class ApplicationController < ActionController::Base
 
28
    #     before_filter :set_account, :authenticate
 
29
    #
 
30
    #     protected
 
31
    #       def set_account
 
32
    #         @account = Account.find_by_url_name(request.subdomains.first)
 
33
    #       end
 
34
    #
 
35
    #       def authenticate
 
36
    #         case request.format
 
37
    #         when Mime::XML, Mime::ATOM
 
38
    #           if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
 
39
    #             @current_user = user
 
40
    #           else
 
41
    #             request_http_basic_authentication
 
42
    #           end
 
43
    #         else
 
44
    #           if session_authenticated?
 
45
    #             @current_user = @account.users.find(session[:authenticated][:user_id])
 
46
    #           else
 
47
    #             redirect_to(login_url) and return false
 
48
    #           end
 
49
    #         end
 
50
    #       end
 
51
    #   end
 
52
    #
 
53
    # In your integration tests, you can do something like this:
 
54
    #
 
55
    #   def test_access_granted_from_xml
 
56
    #     get(
 
57
    #       "/notes/1.xml", nil,
 
58
    #       'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
 
59
    #     )
 
60
    #
 
61
    #     assert_equal 200, status
 
62
    #   end
 
63
    #
 
64
    # === Simple \Digest example
 
65
    #
 
66
    #   require 'digest/md5'
 
67
    #   class PostsController < ApplicationController
 
68
    #     REALM = "SuperSecret"
 
69
    #     USERS = {"dhh" => "secret", #plain text password
 
70
    #              "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))}  #ha1 digest password
 
71
    #
 
72
    #     before_filter :authenticate, :except => [:index]
 
73
    #
 
74
    #     def index
 
75
    #       render :text => "Everyone can see me!"
 
76
    #     end
 
77
    #
 
78
    #     def edit
 
79
    #       render :text => "I'm only accessible if you know the password"
 
80
    #     end
 
81
    #
 
82
    #     private
 
83
    #       def authenticate
 
84
    #         authenticate_or_request_with_http_digest(REALM) do |username|
 
85
    #           USERS[username]
 
86
    #         end
 
87
    #       end
 
88
    #   end
 
89
    #
 
90
    # === Notes
 
91
    #
 
92
    # The +authenticate_or_request_with_http_digest+ block must return the user's password
 
93
    # or the ha1 digest hash so the framework can appropriately hash to check the user's
 
94
    # credentials. Returning +nil+ will cause authentication to fail.
 
95
    #
 
96
    # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
 
97
    # the password file or database is compromised, the attacker would be able to use the ha1 hash to
 
98
    # authenticate as the user at this +realm+, but would not have the user's password to try using at
 
99
    # other sites.
 
100
    #
 
101
    # In rare instances, web servers or front proxies strip authorization headers before
 
102
    # they reach your application. You can debug this situation by logging all environment
 
103
    # variables, and check for HTTP_AUTHORIZATION, amongst others.
 
104
    module Basic
 
105
      extend self
 
106
 
 
107
      module ControllerMethods
 
108
        extend ActiveSupport::Concern
 
109
 
 
110
        module ClassMethods
 
111
          def http_basic_authenticate_with(options = {})
 
112
            before_filter(options.except(:name, :password, :realm)) do
 
113
              authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
 
114
                name == options[:name] && password == options[:password]
 
115
              end
 
116
            end
 
117
          end
 
118
        end
 
119
 
 
120
        def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
 
121
          authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
 
122
        end
 
123
 
 
124
        def authenticate_with_http_basic(&login_procedure)
 
125
          HttpAuthentication::Basic.authenticate(request, &login_procedure)
 
126
        end
 
127
 
 
128
        def request_http_basic_authentication(realm = "Application")
 
129
          HttpAuthentication::Basic.authentication_request(self, realm)
 
130
        end
 
131
      end
 
132
 
 
133
      def authenticate(request, &login_procedure)
 
134
        unless request.authorization.blank?
 
135
          login_procedure.call(*user_name_and_password(request))
 
136
        end
 
137
      end
 
138
 
 
139
      def user_name_and_password(request)
 
140
        decode_credentials(request).split(/:/, 2)
 
141
      end
 
142
 
 
143
      def decode_credentials(request)
 
144
        ::Base64.decode64(request.authorization.split(' ', 2).last || '')
 
145
      end
 
146
 
 
147
      def encode_credentials(user_name, password)
 
148
        "Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
 
149
      end
 
150
 
 
151
      def authentication_request(controller, realm)
 
152
        controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
 
153
        controller.response_body = "HTTP Basic: Access denied.\n"
 
154
        controller.status = 401
 
155
      end
 
156
    end
 
157
 
 
158
    module Digest
 
159
      extend self
 
160
 
 
161
      module ControllerMethods
 
162
        def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
 
163
          authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
 
164
        end
 
165
 
 
166
        # Authenticate with HTTP Digest, returns true or false
 
167
        def authenticate_with_http_digest(realm = "Application", &password_procedure)
 
168
          HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
 
169
        end
 
170
 
 
171
        # Render output including the HTTP Digest authentication header
 
172
        def request_http_digest_authentication(realm = "Application", message = nil)
 
173
          HttpAuthentication::Digest.authentication_request(self, realm, message)
 
174
        end
 
175
      end
 
176
 
 
177
      # Returns false on a valid response, true otherwise
 
178
      def authenticate(request, realm, &password_procedure)
 
179
        request.authorization && validate_digest_response(request, realm, &password_procedure)
 
180
      end
 
181
 
 
182
      # Returns false unless the request credentials response value matches the expected value.
 
183
      # First try the password as a ha1 digest password. If this fails, then try it as a plain
 
184
      # text password.
 
185
      def validate_digest_response(request, realm, &password_procedure)
 
186
        secret_key  = secret_token(request)
 
187
        credentials = decode_credentials_header(request)
 
188
        valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
 
189
 
 
190
        if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
 
191
          password = password_procedure.call(credentials[:username])
 
192
          return false unless password
 
193
 
 
194
          method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
 
195
          uri    = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
 
196
 
 
197
          [true, false].any? do |trailing_question_mark|
 
198
            [true, false].any? do |password_is_ha1|
 
199
              _uri = trailing_question_mark ? uri + "?" : uri
 
200
              expected = expected_response(method, _uri, credentials, password, password_is_ha1)
 
201
              expected == credentials[:response]
 
202
            end
 
203
          end
 
204
        end
 
205
      end
 
206
 
 
207
      # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
 
208
      # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
 
209
      # of a plain-text password.
 
210
      def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
 
211
        ha1 = password_is_ha1 ? password : ha1(credentials, password)
 
212
        ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
 
213
        ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
 
214
      end
 
215
 
 
216
      def ha1(credentials, password)
 
217
        ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
 
218
      end
 
219
 
 
220
      def encode_credentials(http_method, credentials, password, password_is_ha1)
 
221
        credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
 
222
        "Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
 
223
      end
 
224
 
 
225
      def decode_credentials_header(request)
 
226
        decode_credentials(request.authorization)
 
227
      end
 
228
 
 
229
      def decode_credentials(header)
 
230
        Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
 
231
          key, value = pair.split('=', 2)
 
232
          [key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')]
 
233
        end]
 
234
      end
 
235
 
 
236
      def authentication_header(controller, realm)
 
237
        secret_key = secret_token(controller.request)
 
238
        nonce = self.nonce(secret_key)
 
239
        opaque = opaque(secret_key)
 
240
        controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
 
241
      end
 
242
 
 
243
      def authentication_request(controller, realm, message = nil)
 
244
        message ||= "HTTP Digest: Access denied.\n"
 
245
        authentication_header(controller, realm)
 
246
        controller.response_body = message
 
247
        controller.status = 401
 
248
      end
 
249
 
 
250
      def secret_token(request)
 
251
        secret = request.env["action_dispatch.secret_token"]
 
252
        raise "You must set config.secret_token in your app's config" if secret.blank?
 
253
        secret
 
254
      end
 
255
 
 
256
      # Uses an MD5 digest based on time to generate a value to be used only once.
 
257
      #
 
258
      # A server-specified data string which should be uniquely generated each time a 401 response is made.
 
259
      # It is recommended that this string be base64 or hexadecimal data.
 
260
      # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
 
261
      #
 
262
      # The contents of the nonce are implementation dependent.
 
263
      # The quality of the implementation depends on a good choice.
 
264
      # A nonce might, for example, be constructed as the base 64 encoding of
 
265
      #
 
266
      # => time-stamp H(time-stamp ":" ETag ":" private-key)
 
267
      #
 
268
      # where time-stamp is a server-generated time or other non-repeating value,
 
269
      # ETag is the value of the HTTP ETag header associated with the requested entity,
 
270
      # and private-key is data known only to the server.
 
271
      # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
 
272
      # reject the request if it did not match the nonce from that header or
 
273
      # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
 
274
      # The inclusion of the ETag prevents a replay request for an updated version of the resource.
 
275
      # (Note: including the IP address of the client in the nonce would appear to offer the server the ability
 
276
      # to limit the reuse of the nonce to the same client that originally got it.
 
277
      # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
 
278
      # Also, IP address spoofing is not that hard.)
 
279
      #
 
280
      # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
 
281
      # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
 
282
      # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
 
283
      # of this document.
 
284
      #
 
285
      # The nonce is opaque to the client. Composed of Time, and hash of Time with secret
 
286
      # key from the Rails session secret generated upon creation of project. Ensures
 
287
      # the time cannot be modified by client.
 
288
      def nonce(secret_key, time = Time.now)
 
289
        t = time.to_i
 
290
        hashed = [t, secret_key]
 
291
        digest = ::Digest::MD5.hexdigest(hashed.join(":"))
 
292
        ::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
 
293
      end
 
294
 
 
295
      # Might want a shorter timeout depending on whether the request
 
296
      # is a PUT or POST, and if client is browser or web service.
 
297
      # Can be much shorter if the Stale directive is implemented. This would
 
298
      # allow a user to use new nonce without prompting user again for their
 
299
      # username and password.
 
300
      def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
 
301
        t = ::Base64.decode64(value).split(":").first.to_i
 
302
        nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
 
303
      end
 
304
 
 
305
      # Opaque based on random generation - but changing each request?
 
306
      def opaque(secret_key)
 
307
        ::Digest::MD5.hexdigest(secret_key)
 
308
      end
 
309
 
 
310
    end
 
311
 
 
312
    # Makes it dead easy to do HTTP Token authentication.
 
313
    #
 
314
    # Simple Token example:
 
315
    #
 
316
    #   class PostsController < ApplicationController
 
317
    #     TOKEN = "secret"
 
318
    #
 
319
    #     before_filter :authenticate, :except => [ :index ]
 
320
    #
 
321
    #     def index
 
322
    #       render :text => "Everyone can see me!"
 
323
    #     end
 
324
    #
 
325
    #     def edit
 
326
    #       render :text => "I'm only accessible if you know the password"
 
327
    #     end
 
328
    #
 
329
    #     private
 
330
    #       def authenticate
 
331
    #         authenticate_or_request_with_http_token do |token, options|
 
332
    #           token == TOKEN
 
333
    #         end
 
334
    #       end
 
335
    #   end
 
336
    #
 
337
    #
 
338
    # Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
 
339
    # the regular HTML interface is protected by a session approach:
 
340
    #
 
341
    #   class ApplicationController < ActionController::Base
 
342
    #     before_filter :set_account, :authenticate
 
343
    #
 
344
    #     protected
 
345
    #       def set_account
 
346
    #         @account = Account.find_by_url_name(request.subdomains.first)
 
347
    #       end
 
348
    #
 
349
    #       def authenticate
 
350
    #         case request.format
 
351
    #         when Mime::XML, Mime::ATOM
 
352
    #           if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
 
353
    #             @current_user = user
 
354
    #           else
 
355
    #             request_http_token_authentication
 
356
    #           end
 
357
    #         else
 
358
    #           if session_authenticated?
 
359
    #             @current_user = @account.users.find(session[:authenticated][:user_id])
 
360
    #           else
 
361
    #             redirect_to(login_url) and return false
 
362
    #           end
 
363
    #         end
 
364
    #       end
 
365
    #   end
 
366
    #
 
367
    #
 
368
    # In your integration tests, you can do something like this:
 
369
    #
 
370
    #   def test_access_granted_from_xml
 
371
    #     get(
 
372
    #       "/notes/1.xml", nil,
 
373
    #       :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
 
374
    #     )
 
375
    #
 
376
    #     assert_equal 200, status
 
377
    #   end
 
378
    #
 
379
    #
 
380
    # On shared hosts, Apache sometimes doesn't pass authentication headers to
 
381
    # FCGI instances. If your environment matches this description and you cannot
 
382
    # authenticate, try this rule in your Apache setup:
 
383
    #
 
384
    #   RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
 
385
    module Token
 
386
      extend self
 
387
 
 
388
      module ControllerMethods
 
389
        def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
 
390
          authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
 
391
        end
 
392
 
 
393
        def authenticate_with_http_token(&login_procedure)
 
394
          Token.authenticate(self, &login_procedure)
 
395
        end
 
396
 
 
397
        def request_http_token_authentication(realm = "Application")
 
398
          Token.authentication_request(self, realm)
 
399
        end
 
400
      end
 
401
 
 
402
      # If token Authorization header is present, call the login procedure with
 
403
      # the present token and options.
 
404
      #
 
405
      # controller      - ActionController::Base instance for the current request.
 
406
      # login_procedure - Proc to call if a token is present. The Proc should
 
407
      #                   take 2 arguments:
 
408
      #                     authenticate(controller) { |token, options| ... }
 
409
      #
 
410
      # Returns the return value of `&login_procedure` if a token is found.
 
411
      # Returns nil if no token is found.
 
412
      def authenticate(controller, &login_procedure)
 
413
        token, options = token_and_options(controller.request)
 
414
        unless token.blank?
 
415
          login_procedure.call(token, options)
 
416
        end
 
417
      end
 
418
 
 
419
      # Parses the token and options out of the token authorization header. If
 
420
      # the header looks like this:
 
421
      #   Authorization: Token token="abc", nonce="def"
 
422
      # Then the returned token is "abc", and the options is {:nonce => "def"}
 
423
      #
 
424
      # request - ActionDispatch::Request instance with the current headers.
 
425
      #
 
426
      # Returns an Array of [String, Hash] if a token is present.
 
427
      # Returns nil if no token is found.
 
428
      def token_and_options(request)
 
429
        if request.authorization.to_s[/^Token (.*)/]
 
430
          values = Hash[$1.split(',').map do |value|
 
431
            value.strip!                      # remove any spaces between commas and values
 
432
            key, value = value.split(/\=\"?/) # split key=value pairs
 
433
            value.chomp!('"')                 # chomp trailing " in value
 
434
            value.gsub!(/\\\"/, '"')          # unescape remaining quotes
 
435
            [key, value]
 
436
          end]
 
437
          [values.delete("token"), values.with_indifferent_access]
 
438
        end
 
439
      end
 
440
 
 
441
      # Encodes the given token and options into an Authorization header value.
 
442
      #
 
443
      # token   - String token.
 
444
      # options - optional Hash of the options.
 
445
      #
 
446
      # Returns String.
 
447
      def encode_credentials(token, options = {})
 
448
        values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
 
449
          "#{key}=#{value.to_s.inspect}"
 
450
        end
 
451
        "Token #{values * ", "}"
 
452
      end
 
453
 
 
454
      # Sets a WWW-Authenticate to let the client know a token is desired.
 
455
      #
 
456
      # controller - ActionController::Base instance for the outgoing response.
 
457
      # realm      - String realm to use in the header.
 
458
      #
 
459
      # Returns nothing.
 
460
      def authentication_request(controller, realm)
 
461
        controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
 
462
        controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
 
463
      end
 
464
    end
 
465
  end
 
466
end