16

I have an application developed in Rails and I am trying to see the attributes in the HTTP header.

Is there any way to read these attributes? Where are they stored?

Someone mentioned request.headers. Is this correct? I am not able to see any attributes inside this array.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
delpha
  • 931
  • 1
  • 8
  • 23

4 Answers4

45

request.headers does not return a hash, but an instance of ActionDispatch::Http::Headers, which is a wrapper around rack env.

ActionDispatch::Http::Headers implements many methods like [] and []= which make it behave like a hash, but it doesn't override the default inspect, hence you can't see the key-value pairs by just p or pp it.

You can, however, see the request headers in the rack env:

pp request.headers.env.select{|k, _| k =~ /^HTTP_/}

Remember that the request headers in rack env are the upcased, underscored and HTTP_ prefixed version of the original http request headers.

UPDATE

Actually there are a finite set of request headers that are not prefixed HTTP_. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES. I list them below:

    AUTH_TYPE
    CONTENT_LENGTH
    CONTENT_TYPE
    GATEWAY_INTERFACE
    HTTPS
    PATH_INFO
    PATH_TRANSLATED
    QUERY_STRING
    REMOTE_ADDR
    REMOTE_HOST
    REMOTE_IDENT
    REMOTE_USER
    REQUEST_METHOD
    SCRIPT_NAME
    SERVER_NAME
    SERVER_PORT
    SERVER_PROTOCOL
    SERVER_SOFTWARE

So the full version of listing request headers would be

pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/}
Aetherus
  • 8,720
  • 1
  • 22
  • 36
  • 2
    I am a bit confused, cause I keep getting all the attributes prefixed with `HTTP`, why I can't I access it with something like `response['Cache-Control']` – delpha Sep 04 '15 at 20:42
  • 2
    @user3433309 You absolutely can access the request headers like `request.headers['Authorization']`. Rails wraps the rack env for just this reason. You can take a look at the source code of `ActionDispatch::Http::Headers`, it's very simple. – Aetherus Sep 04 '15 at 23:53
  • I was able to access an attribute, an OAuth2 signature in my case, using either, `request.headers.env['HTTP_X_PROVIDER_SIGNATURE']` or `request.headers['X-Provider-Signature']`. A Rails5 application. – Mark Kreyman Feb 09 '17 at 18:47
9

This code solved my question request.env["HTTP_MY_HEADER"]. The trick was that I had to prefix my header's name with HTTP

delpha
  • 931
  • 1
  • 8
  • 23
7

I've noticed in Rails 5 they now expect headers to be spelled like this in the request:

Access-Token

Before they are transformed into:

HTTP_ACCESS_TOKEN

In Rails. Doing ACCESS_TOKEN will no longer work.

zachaysan
  • 1,726
  • 16
  • 32
-3

You can see hash of actual http headers using @_headers in controller.

BitOfUniverse
  • 5,903
  • 1
  • 34
  • 38