
Rails Security
CSRF protection, SQL injection, XSS, mass assignment, secrets management, HTTPS
1What mechanism does Rails use by default to protect against CSRF attacks?
What mechanism does Rails use by default to protect against CSRF attacks?
回答
Rails generates a unique CSRF token per session and automatically includes it in forms via a hidden field. This token is verified server-side for every non-GET request. The form_with helper automatically inserts this token, and protect_from_forgery is enabled by default in ApplicationController.
2How to disable CSRF protection for a specific action in an API controller?
How to disable CSRF protection for a specific action in an API controller?
回答
The skip_before_action :verify_authenticity_token method disables CSRF verification for specific actions. This is common for APIs using token-based authentication (JWT, API key) rather than sessions. It's recommended to limit this exception to strictly necessary actions using the only option.
3What vulnerability is exploited in this code: User.where("name = '#{params[:name]}'")?
What vulnerability is exploited in this code: User.where("name = '#{params[:name]}'")?
回答
Direct params interpolation in a SQL query allows SQL injection. An attacker can send name="'; DROP TABLE users; --" to execute arbitrary SQL code. Use ActiveRecord placeholders instead: User.where(name: params[:name]) or User.where("name = ?", params[:name]).
Which ActiveRecord method automatically protects against SQL injection?
How does Rails automatically protect against XSS attacks in ERB views?
+19 面接問題