1 使用
这个Module提供了一个简单的方法进行基于HTTP的验证,个人感觉没有太大的帮助,反而增加了复杂度,不如自己实现简单:
  1. class PostsController < ApplicationController
  2.          USER_NAME, PASSWORD = "dhh""secret"
  3.        
  4.          before_filter :authenticate:except => [ :index ]
  5.        
  6.          def index
  7.            render :text => "Everyone can see me!"
  8.          end
  9.        
  10.          def edit
  11.            render :text => "I'm only accessible if you know the password"
  12.          end
  13.        
  14.          private
  15.            def authenticate
  16.              authenticate_or_request_with_http_basic do |user_name, password| 
  17.                user_name == USER_NAME && password == PASSWORD
  18.              end
  19.            end
  20.        end

  1.        class ApplicationController < ActionController::Base
  2.          before_filter :set_account:authenticate
  3.        
  4.          protected
  5.            def set_account
  6.              @account = Account.find_by_url_name(request.subdomains.first)
  7.            end
  8.        
  9.            def authenticate
  10.              case request.format
  11.              when Mime::XML, Mime::ATOM
  12.                if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
  13.                  @current_user = user
  14.                else
  15.                  request_http_basic_authentication #执行验证失败
  16.                end
  17.              else
  18.                if session_authenticated?
  19.                  @current_user = @account.users.find(session[:authenticated][:user_id])
  20.                else
  21.                  redirect_to(login_url) and return false
  22.                end
  23.              end
  24.            end
  25.        end
  1. # In your integration tests, you can do something like this:
  2.     
  3.        def test_access_granted_from_xml
  4.          get(
  5.            "/notes/1.xml"nil
  6.            :authorization => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
  7.          )
  8.      
  9.          assert_equal 200, status
  10.        end
  11.       
  12.       
  13.     # On shared hosts, Apache sometimes doesn't pass authentication headers to
  14.     # FCGI instances. If your environment matches this description and you cannot
  15.     # authenticate, try this rule in your Apache setup:
  16.     
  17.     #   RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]



2 实现
  1.     module Basic
  2.       extend self
  3.       module ControllerMethods
  4.         # HTTP验证方法 验证失败后将执行后半段函数
  5.         def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
  6.           authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
  7.         end
  8.         # 验证主方法
  9.        def authenticate_with_http_basic(&login_procedure)
  10.           HttpAuthentication::Basic.authenticate(self, &login_procedure)
  11.         end
  12.         # 验证失败
  13.        def request_http_basic_authentication(realm = "Application")
  14.           HttpAuthentication::Basic.authentication_request(self, realm)
  15.         end
  16.       end
  17.       def authenticate(controller, &login_procedure)
  18.         unless authorization(controller.request).blank?
  19.           login_procedure.call(*user_name_and_password(controller.request))
  20.         end
  21.       end
  22.       def user_name_and_password(request) # 从request中获取username,password
  23.         decode_credentials(request).split(/:/, 2)
  24.       end
  25.   
  26.       def authorization(request) # 验证request是否设置并且返回验证字符串
  27.         request.env['HTTP_AUTHORIZATION']   ||
  28.         request.env['X-HTTP_AUTHORIZATION'] ||
  29.         request.env['X_HTTP_AUTHORIZATION'] ||
  30.         request.env['REDIRECT_X_HTTP_AUTHORIZATION']
  31.       end
  32.     
  33.       # 下面两个方法是加密和解码过程
  34.       def decode_credentials(request)
  35.         ActiveSupport::Base64.decode64(authorization(request).split.last || '')
  36.       end
  37.       def encode_credentials(user_name, password)
  38.         "Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
  39.       end
  40.       def authentication_request(controller, realm)
  41.         controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
  42.         controller.send! :render:text => "HTTP Basic: Access denied./n":status => :unauthorized
  43.       end
  44.     end


Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐