Search code examples
ruby-on-railsauthorizationclearance

Verifying user is authorized after using redirect_back


I have a method that creates a new user session and will redirect back to the previous screen after successful login. It has introduced a security issue where someone can type in a url navigate to a page they shouldn't have access to. The app will direct them to login, but after logging with valid credentials (just not the proper level of clearance) it will redirect them to the page they had manually typed into the url. How can I verify that redirect_back isn't sending a user to a page they shouldn't have access to?

Here is the session create method:

 def create
    @user = authenticate(params)
    sign_in(@user) do |status|
      if status.success?
        redirect_back root_path
      else
        flash.now.alert = status.failure_message
        render :new, status: :unauthorized
      end
    end
  end

Is there a way to see what address it will be sending them back to because I could just do something like

if back_url.includes? "admin"
  redirect_to root_path
end



Solution

  • You can’t rely on URL obscurity for security of your application. Your admin routes or controllers should be protected so they can only be accessed by signed in admins.

    You can do this with a route constraint in your routes file (my preference) or a before action that is consistently applied across all of your admin controllers that returns a 403 if the current user is not an admin.