Search code examples
ruby-on-railsruby-on-rails-4cancan

CanCan skip_authorization_check not working with rails json api


I'm creating an app and I want to expose the create method in this controller as an api endpoint.

This does not work and shows the error You are not authorized to access this page. Why does the skip_authorization_check not get honored?

class AccountsController < ApplicationController

    load_and_authorize_resource
    skip_authorization_check :only => [:invalid_site, :create]


...

    # POST /accounts
    # POST /accounts.json
    def create

    puts "in create"
        #authorize! :create, current_user, :message => 'Not authorized as an administrator.'
        @account = Account.new(account_params)

        respond_to do |format|
            if @account.save
                format.html { redirect_to @account, notice: 'Account was successfully created.' }
                format.json { render action: 'show', status: :created, location: @account }
            else
                format.html { render action: 'new' }
                format.json { render json: @account.errors, status: :unprocessable_entity }
            end
        end
    end

...

    private

        # Never trust parameters from the scary internet, only allow the white list through.
        def account_params
      puts params.inspect
            params.require(:account).permit(:subdomain, :billing_email)
        end
end

Solution

  • Seems I also had to add skip_load_and_authorize_resource :only => :create. If someone could more clearly explain all these different skip methods that'd be helpful to the rest of the googlers: http://rubydoc.info/github/CanCanCommunity/cancancan/master/frames/CanCan/ControllerAdditions/ClassMethods