## Security If you were to publish your blog online, anybody would be able to add, edit and delete posts or delete comments. Rails provides a very simple HTTP authentication system that will work nicely in this situation. First, we enable simple HTTP based authentication in our `app/controllers/application_controller.rb`: @@@ ruby class ApplicationController < ActionController::Base protect_from_forgery private def authenticate authenticate_or_request_with_http_basic do |user_name, password| user_name == 'admin' && password == 'password' end end end @@@ You can obviously change the username and password to whatever you want. We put this method inside of `ApplicationController` so that it is available to all of our controllers. Then in the `PostsController` we need to have a way to block access to the various actions if the person is not authenticated, here we can use the Rails `before_filter` method, which allows us to specify that Rails must run a method and only then allow access to the requested action if that method allows it. To use the before filter, we specify it at the top of our `PostsController`, in this case, we want the user to be authenticated on every action, except for `index` and `show`, so we write that: @@@ ruby class PostsController < ApplicationController before_filter :authenticate, :except => [:index, :show] # GET /posts # GET /posts.xml def index @posts = Post.all respond_to do |format| # snipped for brevity @@@
We also only want to allow authenticated users to delete comments, so in the `CommentsController` we write: @@@ ruby class CommentsController < ApplicationController before_filter :authenticate, :only => :destroy def create @post = Post.find(params[:post_id]) # snipped for brevity @@@ Now if you try to create a new post, you will be greeted with a basic HTTP Authentication challenge.