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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning nil at each validation gate keeps a parser flat and readable instead of deeply nested.
- 2Rescuing the specific exception from Base64 decoding turns malformed input into a clean nil rather than a crash.
- 3A keyword-init Struct gives structured, named output without the boilerplate of a full class.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-http-basic-auth-headers-in-ruby-explained-ruby-f494/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.