Search code examples
rubyauthenticationhttp-headerssinatra

Authenticate using headers in Sinatra


How can I compare headers in sinatra and halt the code/script if one of the headers didn't match?

Let's say I have a header named TOKEN: 666 I want to compare any request being made to sinatra and check "TOKEN" if exist and equals to "666" then proceed with the code, if not just return 401.


Solution

  • The answer is simple:

    By default, Sinatra listens on port 4567, so I just made sure it's binding to all the interfaces just in case i want to call it from its external IP address and disabled any verbose error output as follow:

    listener.rb

    require "sinatra"
    
    set :bind, "0.0.0.0"
    disable :show_exceptions
    disable :raise_errors
    
    post "/" do
    
      # Check if the header matches
      # If it did not match then halt and return code 401 Unauthorized
    
      if request.env["HTTP_custom_header_name"] != "verystrongpassword"
        halt 401
      end
    
      #the rest of your code goes here
    
      status :ok
    
    end
    

    Note that when comparing header value , HTTP must always be included and then goes the name of your header - Link

    Example

    require "sinatra"
    
    set :bind, "0.0.0.0"
    disable :show_exceptions
    disable :raise_errors
    
    post "/" do
    
      # Check if the header matches
      # If it did not match then halt and return code 401 Unauthorized
    
      if request.env["HTTP_X_GIT_SECRET"] != "d4c74594d841139328695756648b6bd6"
        halt 401
      end
    
      data = JSON.parse request.body.read
      p data
    
      status :ok
    
    end
    

    Where X_GIT_SECRET is a header name

    Extra

    if you don't know what is the name of the header being sent to sinatra then you may check all the request content by putting the following before the if statement up:

    p request.env

    and then try sending a request again, find your header and do the comparison based on it.

    Note: status :ok aka 200 OK, was set at the end of the block because when someone sends a request to sinatra it should return something, else an 500 internal server error would occur.