Access Headers from Sinatra

I am trying to access the headers in a filter in Sinatra. My request includes the header "HTTP_AUTH", however I cannot access it. My filter

before do halt 403 unless request['HTTP_AUTH'] == 'test' end 

It works correctly with my rack test.

 browser.get '/mypath', "CONTENT_TYPE" => "application/json", "HTTP_AUTH" => 'test' 

But when I try from other sources, I can’t access it. If I puts request.env , I see that the token is in the request, but I can’t access it.

 "HTTP_CONNECTION"=>"close", "HTTP_AUTH"=>"test", "HTTP_ACCEPT"=>"application/json", 

What am I doing wrong?

+5
source share
2 answers

Try using the before block with the headers method:

 before do headers "HTTP_AUTH" => "test" headers "Content-Type" => "text/html; charset=utf-8" end 

or in request:

 get '/' do headers['HTTP_AUTH'] = "test" headers['Cache-Control'] = 'public, max-age=600' puts headers # show headers on this request end 

Use headers only with hash

+9
source

I just wanted to add that if you use headers , it will not show custom headers. For example, I set up my own header called X-CSRF-Token, which I send to every AJAX request, and this one will not appear in this hash. If you need to access custom headers, you will find them through request.env , for example:

 post '/' do header_token = request.env["HTTP_X_CSRF_TOKEN"] end 

(Note that the rack changes the X-CSRF token to HTTP_X_CSRF_TOKEN)

+17
source

Source: https://habr.com/ru/post/1201796/


All Articles