How to configure to accept authentication token in HTTP header?

Currently, devise is configured to accept token authentication through a URL, and curl works well

curl 'http://localhost/index.json?auth_token=TOKENVALUE' 

Now, I would like to pass TOKENVALUE via an HTTP header instead of a URL, how can I configure to get TOKENVALUE from an HTTP header or URL? Thus, both the above and the following curl requests will be executed:

 curl 'http://localhost/index.json' -H 'Authorization: Token token="TOKENVALUE"' 

as shown in this railscast .

+6
source share
5 answers

There seems to be no such configuration in the configuration. But there is another person’s decision. See Using auth_token from request headers instead of POST / PUT parameters with Rails 3 / dev

+1
source

First add this to your gemfile https://github.com/stvp/devise_header_token , then you can add its configuration to your config / initializers / devise.rb

 # Configuration for :token_authenticatable # Defines name of the authentication token params key config.token_authentication_key = 'AUTH-TOKEN' 
+1
source

Devise allows you to authenticate an authentication token through Basic Auth. If you look at the source , you will see the following:

For headers, you can use basic authentication, passing a token as a username and an empty password. Since some clients may require a password, you can pass β€œX” as a password and it will simply be ignored.

+1
source

Since this question was asked, the situation has changed since this device no longer has a built-in token authentication feature. It was extracted into a separate gem, deves-token_authenticatable. I use this gem and wanted to do the same as the one who asked the question.

I realized that I had to install this in my /initializers/devise.rb configuration:

config.http_authenticatable = true

I tried this through curl and it worked. In my RSpec tests, I was able to put the token in the HTTP header as follows:

 user = FactoryGirl.create(:user) header = ActionController::HttpAuthentication::Token.encode_credentials( user.authentication_token) get "/api/v1/your_url", { }, { 'Accept' => 'application/json', 'Authorization' => header } 

Hope this helps someone out there!

+1
source

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


All Articles