create a http server and parse authorization headers in ruby

To create an HTTP server in Ruby, you can use the built-in WEBrick library. Here's an example:

main.rb
require 'webrick'

server = WEBrick::HTTPServer.new(Port: 8000)

server.mount_proc '/' do |req, res|
  auth_header = req['Authorization']
  if auth_header
    # Parse the authorization header
    auth_type, auth_credentials = auth_header.split(' ')
    if auth_type == 'Basic'
      username, password = Base64.decode64(auth_credentials).split(':')
      # Authenticate the user
      # ...
    end
  end
  
  res.body = 'Hello, world!'
end

trap('INT') { server.shutdown }
server.start
487 chars
22 lines

In this example, we create an HTTP server that listens on port 8000. We then define a proc to handle incoming requests to the root URL ('/'). In this proc, we extract the Authorization header from the request and parse it to extract the username and password. We then authenticate the user based on those credentials.

Note that this example assumes that the Authorization header is in the Basic format. If you're expecting other types of authorization headers (e.g. Bearer for OAuth tokens), you'll need to modify the auth_type and auth_credentials variables accordingly.

gistlibby LogSnag