Sinatra - API - Authentication

后端 未结 3 1790
孤城傲影
孤城傲影 2020-12-22 17:28

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

3条回答
  •  时光说笑
    2020-12-22 17:50

    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
    

    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
    

提交回复
热议问题