31

After reading the following question (Authorization header in Ruby on Rails accessed with key HTTP_AUTHORIZATION instead of Authorization?) I have a similar problem as the OP, but the proposed answer does not seem to solve mine.

I define a custom header as such in a call to my locally hosted server (through Postman):

@Igor: I actually use Postman, so I just added the curl code to demonstrate what I did. I guess it would be better to include a screenshot:

enter image description here

And this is the code in my controller which tries to read said header:

def authenticate_through_header
  custom_header_value = request.headers['custom_header']
end

However, this return nil. On the other hand, request.headers['HTTP_CUSTOM_HEADER'] returns the value. According to the question I linked to initially, I should be able to get the value through passing the name within the brackets [ ] - is this something which has been changed in newer Rails versions?

Cheers :-)

Update: It also works to access the variable in the following way: request.headers['custom-header']. So apparently it works to replace the underscore with a hyphen, which seems weird.

1

2 Answers 2

45

Yes, it has changed in Rails 4. Take a look at the Http::Headers code.

Now custom variables are always prepended with HTTP_ and _ in your variables are replaced with -, except for CGI variables.

HTH

EDIT: Just checked again, - in variables are getting replaced with _ and being prepended with HTTP_. In above link, check line number 91-94:

key = key.upcase.tr('-', '_')
Sign up to request clarification or add additional context in comments.

4 Comments

It's so weird :( Is there any reason why Rails has to do this?
ahh.. wasted half hour and then found this. thanks !
Does anybody know why rails is doing this starting in v4? It seems to me based on a quick search that "X-My-Header" is the commonly accepted header convention. Why break it?
Also be aware that nginx, by default, blockers headers with underscores in them.
0

The answer is right, but I thought I'd add a note for people struggling with this.

If you binding.pry into your Rails controller, you can use

request.headers.to_h

This will get you a complete list of all of the headers. This makes it easier to track down that, for example, your header authentication_token has been translated into HTTP_AUTHENTICATION_TOKEN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.