netwire
netwire

Reputation: 7225

Devise authenticate_user! fails with POST / DELETE REST calls

I'm using Devise to authenticate user via the standard implementation. Once a user logs in, he/she can call an REST API that uses the same controller (and thus also Devise). The controller looks like this:

class FriendController < ApplicationController
  before_filter :authenticate_user!
  def create
    ...
  end
  def destroy
    ...
  end
  def index
    ...
  end
end

I got the index action to work with authenticated_user!. In this case, if a user is authenticated, index will return data with 200 Status Code. If a user isn't authenticated, index returns Unauthorized with 40x Status Code.

However, when I'm calling create or destroy via POST and DELETE, it automatically logs me out of the application and returns 40x Unauthorized error. Anyone seen this before? Any ideas?

Here's the route.rb

  resources :users do
    resources :friends, only: [:index, :friended_me, :create, :destroy]
  end

For example, does this needs to be within devise_scope :users block?

Upvotes: 1

Views: 629

Answers (1)

netwire
netwire

Reputation: 7225

I figured out why this is happening. In ApplicationController, if protect_from_forgery is enabled. The API calls for POST/PUT/DELETE will check for auth_token. If it's not provided, it'll fail. However, for GET, if it's not provided, the action will still proceed if user is logged in.

The fix is to use the auth_token generated by resource.reset_authentication_token! after overriding SessionsController#create

Upvotes: 1

Related Questions