1 require 'abstract_unit'
3 class HttpBasicAuthenticationTest
< ActionController
::TestCase
4 class DummyController
< ActionController
::Base
5 before_filter
:authenticate, :only => :index
6 before_filter
:authenticate_with_request, :only => :display
9 render
:text => "Hello Secret"
13 render
:text => 'Definitely Maybe'
19 authenticate_or_request_with_http_basic
do |username
, password
|
20 username
== 'lifo' && password
== 'world'
24 def authenticate_with_request
25 if authenticate_with_http_basic
{ |username
, password
| username
== 'pretty' && password
== 'please' }
28 request_http_basic_authentication("SuperSecret")
33 AUTH_HEADERS
= ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION', 'REDIRECT_X_HTTP_AUTHORIZATION']
37 AUTH_HEADERS
.each
do |header
|
38 test
"successful authentication with #{header.downcase}" do
39 @request.env[header
] = encode_credentials('lifo', 'world')
42 assert_response
:success
43 assert_equal
'Hello Secret', @response.body
, "Authentication failed for request header #{header}"
47 AUTH_HEADERS
.each
do |header
|
48 test
"unsuccessful authentication with #{header.downcase}" do
49 @request.env[header
] = encode_credentials('h4x0r', 'world')
52 assert_response
:unauthorized
53 assert_equal
"HTTP Basic: Access denied.\n", @response.body
, "Authentication didn't fail for request header #{header}"
57 test
"authentication request without credential" do
60 assert_response
:unauthorized
61 assert_equal
"HTTP Basic: Access denied.\n", @response.body
62 assert_equal
'Basic realm="SuperSecret"', @response.headers
['WWW-Authenticate']
65 test
"authentication request with invalid credential" do
66 @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'foo')
69 assert_response
:unauthorized
70 assert_equal
"HTTP Basic: Access denied.\n", @response.body
71 assert_equal
'Basic realm="SuperSecret"', @response.headers
['WWW-Authenticate']
74 test
"authentication request with valid credential" do
75 @request.env['HTTP_AUTHORIZATION'] = encode_credentials('pretty', 'please')
78 assert_response
:success
79 assert
assigns(:logged_in)
80 assert_equal
'Definitely Maybe', @response.body
85 def encode_credentials(username
, password
)
86 "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}"