Rails + Devise HTTP header token -
i have in devise config following line enable token authentication in http header:
config.http_authenticatable = [:token]
however, whenever try access resource, receive 401 when running following:
curl -v -h "accept: application/json" -h "content-type: application/json" -h "authorization: token token=\"c9g52z6n6lpgt5ls6omw\"" http://localhost:3000/api/v1/objects/
as proof token correct, following works:
curl -v -h "accept: application/json" -h "content-type: application/json" http://localhost:3000/api/v1/objects?auth_token=c9g52z6n6lpgt5ls6omw
has managed token authentication in http header working? can't find information on apart from:
http://api.rubyonrails.org/classes/actioncontroller/httpauthentication/token.html https://groups.google.com/forum/#!topic/plataformatec-devise/o3gqgl0yuzo
my implementation based on post , gist.
user.rb
class user < activerecord::base devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable before_create :set_auth_token private def set_auth_token return if auth_token.present? begin self.auth_token = securerandom.hex end while self.class.exists?(auth_token: self.auth_token) end end
api_controller.rb
class apicontroller < applicationcontroller before_action :authenticate protected def authenticate authenticate_token || render_unauthorized end def authenticate_token authenticate_with_http_token |token, options| user = user.find_by(auth_token: token) if user sign_in user, store: false end user end end def render_unauthorized self.headers['www-authenticate'] = 'token realm="application"' render json: 'bad credentials', status: 401 end end
Comments
Post a Comment