Andrew
Andrew

Reputation: 43153

Rails HTTP Basic check for authenticated?

I've been googling this one and haven't turned up anything useful:

Assuming you use http basic auth in Rails is there a simple method to check if the user is authenticated? Ie. a way you can do something like this in a view:

- if http_basic_authenticated?
  # show admin menu

Upvotes: 1

Views: 2055

Answers (4)

ivanxuu
ivanxuu

Reputation: 852

From the oficial code you can extract snipets to use something like this in any controller inherited by ApplicationController:

class ApplicationController < BaseController
  ...
  protected # Only inherited controllers can call authorized?
  def authorized?
    request.authorization.present? && (request.authorization.split(' ', 2).first == 'Basic')
  end
...
end

Upvotes: 1

Oscar Del Ben
Oscar Del Ben

Reputation: 4515

Try this:

class ApplicationController < ..

  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      @authenticated = username == "foo" && password == "bar"
    end
  end

  def authenticated?
    @authenticated
  end
  helper_method :authenticated?

end

You can now use authenticated in your view.

Please write tests!

Upvotes: 4

Marcus
Marcus

Reputation: 6849

well, as I could know, there's no way to tell a view that the request is not authenticated, you could just tell the view that it is authenticated, but why? let's see the process of a request:

  1. Client Request
  2. Controller
  3. View

and in the 2nd step, the particular controller's method, which is before-filtered by the authentication method, that is, if you can go to the 3rd step -- the view, the request must be authenticated.

Upvotes: 0

David Underwood
David Underwood

Reputation: 4976

Use a session parameter accessible through a method defined in your ApplicationController.

class ApplicationController < BaseController

...

  def authorize
    session[:authorized] = true
  end

  def http_basic_authenticated?
    session[:authorized]
  end

  def end_session
    session[:authorized] = nil
  end

end

P.S. I'm not a security expert, so I can't comment on the suitability of using this in a production environment.

Upvotes: 3

Related Questions