0

During the course of attempting to implement token authentication in Rails, I ran into this behavior:

class AppController < ActionController::Base
    before_filter :restrict_access

    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
        false
      end
    end

This will deny all requests, as expected.

However, if I change "false" to "return false", it accepts all requests.

def restrict_access
  authenticate_or_request_with_http_token do |token, options|
    return false
  end
end 

How is that possible?

1 Answer 1

2

In order to deny the request, before_filter has to call redirect or render.

Now this is how this method looks like:

# File actionpack/lib/action_controller/metal/http_authentication.rb, line 389
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
  authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
end

and what return false does here, is breaking out prematurely from the method (not just the block) before request_http_token_authentication being able to run, and that's the method which actually renders 403 page as shown here: http://apidock.com/rails/ActionController/HttpAuthentication/Token/authentication_request.

So you end up having something like this:

return(false) || request_http_token_authentication(realm)

instead of this:

false || request_http_token_authentication(realm)

That's why you shouldn't use return statements in blocks.

See more here: Using 'return' in a Ruby block

Sign up to request clarification or add additional context in comments.

2 Comments

"That's why you shouldn't use return statements in blocks"- Exactly- I'm an idiot. Great answer, thanks.
return statements in blocks are fine, just you need to understand how to use them! There's more detail to be had here Returning from a Ruby proc: beware of where you land

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.