class PostsController < ApplicationController
TOKEN = "secret"
before_action :authenticate, except: :index
def index
render plain: "Everyone can see me!"
end
def edit
render plain: "I'm only accessible if you know the password"
end
private
def authenticate
# 使用验证
authenticate_or_request_with_http_token do |token, options|
token == TOKEN
end
end
end
再次举例:
class ApplicationController < ActionController::Base
before_action :set_account, :authenticate
protected
def set_account
@account = Account.find_by(url_name: request.subdomains.first)
end
def authenticate
case request.format
when Mime::XML, Mime::ATOM
# 使用验证
if user = authenticate_with_http_token do |t, o|
@account.users.authenticate(t, o)
end
@current_user = user
else
# 使用验证
request_http_token_authentication
end
else
if session_authenticated?
@current_user = @account.users.find(session[:authenticated][:user_id])
else
redirect_to(login_url) and return false
end
end
end
end