ruby 31 lines · 6 steps

Parsing HTTP Basic Auth headers in Ruby

A defensive parser that turns a raw Authorization header into a username/password struct, returning nil at every failure point.

Explained by highlit
1require "base64"
2 
3module Auth
4 module BasicCredentials
5 Credentials = Struct.new(:username, :password, keyword_init: true)
6 
7 module_function
8 
9 def parse(header)
10 return nil if header.nil? || header.empty?
11 
12 scheme, encoded = header.split(" ", 2)
13 return nil unless scheme&.casecmp?("Basic")
14 return nil if encoded.nil? || encoded.strip.empty?
15 
16 decoded = decode(encoded.strip)
17 return nil if decoded.nil?
18 
19 username, password = decoded.split(":", 2)
20 return nil if username.nil? || password.nil?
21 
22 Credentials.new(username: username, password: password)
23 end
24 
25 def decode(encoded)
26 Base64.strict_decode64(encoded).force_encoding(Encoding::UTF_8)
27 rescue ArgumentError
28 nil
29 end
30 end
31end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning nil at each validation gate keeps a parser flat and readable instead of deeply nested.
  2. 2Rescuing the specific exception from Base64 decoding turns malformed input into a clean nil rather than a crash.
  3. 3A keyword-init Struct gives structured, named output without the boilerplate of a full class.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing HTTP Basic Auth headers in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code