西纳特拉 - API - 验证 [英] Sinatra - API - Authentication

查看:303
本文介绍了西纳特拉 - API - 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们将开发在西纳特拉有点API应用程序。什么都可以,以确保API调用的验证选项?

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

推荐答案

西纳特拉没有内置的身份验证支持。有一些宝石可用的,但大多数是专为用户认证(即,用于一个网站)。对于一个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? - 错误通话停止内部,它停止从这个请求。

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

如果你只是想在所有的航线验证,使用之前处理程序:

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

这篇关于西纳特拉 - API - 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆