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?

Yarin
  • 173,523
  • 149
  • 402
  • 512

1 Answers1

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

Community
  • 1
  • 1
Bart
  • 2,606
  • 21
  • 32
  • "That's why you shouldn't use return statements in blocks"- Exactly- I'm an idiot. Great answer, thanks. – Yarin Dec 24 '13 at 04:40
  • `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](https://medium.com/p/returning-from-a-ruby-proc-beware-of-where-you-land-a29add7ddd9d?source=email-1851b7a028dd--writer.postDistributed&sk=5cac3dce3ef9dc67b9060c30b8f1e916) – ComDubh Jun 04 '20 at 14:08