HTTP Basic Authentication--Rails 2.x 版本后的新功能

基本身份验证(HTTP Basic Authentication

互联网产品开发过程中,web应用系统公布的api包括2种

 

1.直接调用

 

2.需要验证

 

多用在公布API接口中。

 

基本身份验证是api在调用的时候,即发送http请求,在HTTP头中传入用户名与密码。

 

 

 

a. 官方例子

     

       class PostsController < ApplicationController
         USER_NAME, PASSWORD = "dhh", "secret"
       
         before_filter :authenticate, :except => [ :index ]
       
         def index
           render :text => "Everyone can see me!"
         end
       
         def edit
           render :text => "I'm only accessible if you know the password"
         end
       
         private
           def authenticate
             authenticate_or_request_with_http_basic do |user_name, password| 
               user_name == USER_NAME && password == PASSWORD
             end
           end
       end

 

b. 一个实例测试

 

    Controller Code

 

before_filter :authenticatedef authenticate

      authenticate_or_request_with_http_basic do |username, password|

            @user = User.authenticate(username, password) # 替换成你自己的逻辑代码

    end

end

 

  Functional Test

 

 

def setup

    @controller = AdminController.new
    @request = ActionController::TestRequest.new
    @response = ActionController::TestResponse.new
    set_basic_authentication

end

def test_basic_authentication_success
    get :index
    assert_response :success
end

def set_basic_authentication

    @request.env['HTTP_AUTHORIZATION'] = ‘Basic ‘ + Base64::b64encode(”taito:123456”) # 这里换成你自己的用户名和密码

end

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值