Fixing the "this cannot include CR/LF" error when doing Basic auth in Ruby

Sometimes, opting for sensible defaults seems obvious. Yet, sometimes, the default and most obvious option isn't the most sensible.

Fixing the "this cannot include CR/LF" error when doing Basic auth in Ruby
Lines, old and new... ish - Photo by Lubo Minar / Unsplash

Today, while testing an integration I'm currently working on for a client, I got the following error:

class: ArgumentError
message: header Authorization has field value "Basic somethingSomethingBase64Encoded", this cannot include CR/LF

This meant that my Authorization header was considered to be invalid, because it supposedly contained a new line character at the end, even though I certainly didn't recall adding any such thing when creating it.

def encoded_credentials
  Base64.encode64("#{@username}:#{@secret}")
end

Looking around online, some suggested simply switching to another authentication mechanism. Which isn't always an option. I also discovered that it just so happens that the Base64 ruby library simply adds a newline every 60 characters when encoding a string. Which can be avoided by using strict_encodeinstead of encode (cf this Github issue). Like that:

def encoded_credentials
  Base64.strict_encode64("#{@username}:#{@secret}")
end

Much better.

And if that doesn't help (spoiler: for me, for some reason, it didn't), you can still take out the heavy artillery good ol' (and slightly dirty) search and replace:

def encoded_credentials
  Base64.encode64("#{@username}:#{@secret}").gsub(/\n/, '')
end

Voilà!

Hope it helped, and the best of days to you!

Edit, January 25th 2023: or you could use Base64.strict_encode64 instead. Just saying.
The essentials of a good conversation.
Cheers! - Photo by Nathan Dumlao / Unsplash