Sinatra - API - Authentication

后端 未结 3 1809
孤城傲影
孤城傲影 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:49

    http://www.secondforge.com/blog/2014/11/05/simple-api-authentication-in-sinatra/ has a slightly more detailed answer that uses user tokens.

    This is one step more complicated than an API key, but is necessary if your API needs authentication to log in a user to do things such as editing a name/email/password, or accessing per-user information. (i.e. "private" API actions). You can also revoke/expire user tokens to let people log out, etc.

    class App < Sinatra::Base
    
      before do
        begin
          if request.body.read(1)
            request.body.rewind
            @request_payload = JSON.parse request.body.read, { symbolize_names: true }
          end
        rescue JSON::ParserError => e
          request.body.rewind
          puts "The body #{request.body.read} was not JSON"
        end
      end
    
      post '/login' do
        params = @request_payload[:user]
    
        user = User.find(email: params[:email])
        if user.password == params[:password] #compare the hash to the string; magic
          #log the user in
        else
          #tell the user they aren't logged in
        end
      end
    end
    

    (It's worth to note that it's more common to read credentials from an HTTP header instead of the JSON body, but the author mentions that.)

提交回复
热议问题