基本身份验证(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