Authorization in Rails: Protecting Every Post Action
Authentication is only the first check
Knowing who signed in does not establish which records they may change. A blog needs separate rules for reading, editing, publishing, and moderation. Write these rules down before implementing controllers so each route enforces the same policy.
before_action :authenticate_user!, only: [:edit, :update]
def update
@post = current_user.posts.find(params[:id])
if @post.update(post_params)
redirect_to @post, status: :see_other
else
render :edit, status: :unprocessable_entity
end
end
Scoping through current_user.posts blocks access to another author's record. If verified posts are locked for editing, add that state check before updating. Keep privileged fields such as role, verified, and user_id out of author strong parameters.
Match the authentication mechanism to the client
For a browser Rails application, session cookies work with the framework's request protections. Preserve CSRF protection for cookie-authenticated state changes. Token authentication for a separate API has different requirements, including token expiry and revocation; adding a token does not remove the need for authorization.
Check every entry point
The same rule must apply to HTML, JSON, background actions, and AI tools. A disabled edit button is helpful interface feedback, but the server still needs to reject a crafted request. Public lists, search, and downloads must respect the visibility policy too.
Test with two authors
Verify that each author can change their own permitted draft and cannot change the other author's record. Add a request that submits privileged parameters. Confirm the operation fails without changing ownership or approval state.
Reference: Securing Rails Applications.
Nhat
リアクション
コメント
サインイン して会話に参加しましょう。