Sinatra - API - 身份验证

问题描述:

我们将在 Sinatra 中开发一个小 API 应用程序.有哪些身份验证选项可用于保护 API 调用?

We going to develop a little API application in Sinatra. What are the authentication options available to secure the API calls?

Sinatra 没有内置身份验证支持.有一些 gems 可用,但大多数都是为用户身份验证而设计的(即用于网站).对于 API,它们似乎有点矫枉过正.制作自己的作品很容易.只需检查每个路由中的请求参数,看看它们是否包含有效的 API 密钥,如果没有,则返回 401 错误.

Sinatra has no built-in authentication support. There are some gems available, but most are designed for user authentication (i.e. for a website). For an API, they seem like overkill. It’s easy enough to make your own. Simply check the request params in each of your routes to see if they contain a valid API key, and if not, return a 401 error.

helpers do
  def valid_key? (key)
    false
  end
end

get "/" do
  error 401 unless valid_key?(params[:key])

  "Hello, world."
end

#  $ irb -r open-uri
#  >> open("http://yourapp.com/api/?key=123")
#  OpenURI::HTTPError: 401 Unauthorized

如果您的 valid_key? 方法返回 false,则在调用 error 之后不会发生任何事情 — error 调用 halt在内部,这会阻止请求继续.

Nothing after the call to error will happen if your valid_key? method returns false — error calls halt internally, which stops the request from continuing.

当然,在每条路线的开头重复检查是不理想的.相反,您可以创建一个小扩展,为您的路由添加条件:

Of course, it’s not ideal to repeat the check at the beginning of each route. Instead, you can create a small extension that adds conditions to your routes:

class App < Sinatra::Base
  register do
    def check (name)
      condition do
        error 401 unless send(name) == true
      end
    end
  end

  helpers do
    def valid_key?
      params[:key].to_i % 2 > 0
    end
  end

  get "/", :check => :valid_key? do
    [1, 2, 3].to_json
  end
end

如果您只想对所有路由进行身份验证,请使用 before 处理程序:

If you just want authentication on all your routes, use a before handler:

before do
  error 401 unless params[:key] =~ /^xyz/
end

get "/" do
  {"e" => mc**2}.to_json
end