Ruby on Rails natively includes many security mechanisms. But a default integration is not enough. Every poorly controlled configuration, every outdated dependency or every unfiltered user input can become an entry point for an attacker. In 2026, web application security is no longer an option reserved for large companies. SMEs, startups and SaaS platforms are targeted just as much. According to OWASP, 94% of web applications have at least one critical vulnerability. Rails provides a solid framework, but it is up to the developer, and to the agency that supports them, to make full use of it. In this article, Akolads presents the essential best practices for securing your Ruby on Rails application: protection against injections, session management, access control, and securing dependencies. Recommendations you can apply directly, with concrete examples.
The most common vulnerabilities in a Rails application
Before fixing, you have to understand. Ruby on Rails applications are exposed to vulnerabilities well documented by the OWASP Top 10. Identifying these vulnerabilities lets you prioritize your security efforts.
Cross-Site Scripting (XSS)
XSS consists of injecting malicious JavaScript code into a web page. An attacker can then steal cookies, redirect the user or perform actions on their behalf. Rails automatically escapes HTML output through ERB, but this protection can be bypassed if you use html_safe carelessly.
Cross-Site Request Forgery (CSRF)
CSRF forces an authenticated user to perform an unwanted action. Rails includes native protection through the CSRF token in every form. Disabling protect_from_forgery, even temporarily, is a critical mistake to avoid at all costs.
SQL injection
SQL injections let an attacker manipulate your database queries. ActiveRecord protects you by default thanks to prepared queries, but using where("email = '#{params[:email]}'") opens an immediate hole. Always use named or positional parameters.
Poor authorization management
Insufficient permission management lets a user access another user's resources. This type of vulnerability, called Broken Access Control, is the number 1 OWASP vulnerability in 2023 and 2024. It often results from a forgotten check in Rails controllers.
“74% of data breaches involve the human element: misconfiguration, developer error, a forgotten access check.” (Verizon DBIR 2024)
Protection against SQL injection and XSS in Rails
Rails offers powerful tools to neutralize these two families of vulnerabilities. You still have to use them correctly and systematically on every line of code.
Using ActiveRecord correctly against SQL injection
The golden rule: never interpolate user parameters directly into an SQL query. ActiveRecord natively provides safe methods.
- Named parameters:
User.where(email: params[:email]): always preferred - Positional parameters:
User.where("email = ?", params[:email]): acceptable - Avoid at all costs:
User.where("email = '#{params[:email]}'"): direct injection - Sanitize methods:
ActiveRecord::Base.sanitize_sqlfor complex cases - Named scopes: they encapsulate the logic and reduce human error
Securing HTML output against XSS
ERB escapes variables by default with <%= %>. But several situations expose you to XSS vulnerabilities:
| Practice | XSS risk | Recommendation |
|---|---|---|
<%= variable %> | Low (automatic escaping) | ✅ Use systematically |
<%= variable.html_safe %> | High | ⚠️ Reserve for trusted HTML only |
<%= raw variable %> | Very high | ❌ Avoid at all costs on user data |
| Content Security Policy (CSP) | Mitigating | ✅ Configure through SecureHeaders |
Setting up a Content Security Policy (CSP)
The CSP is an additional layer of defense against XSS. It tells the browser which script sources are allowed. The secure_headers gem simplifies setting it up in Rails.
Validating and filtering all user input
ActiveRecord validations are not only for data consistency. They also filter out unexpected values. Combine them with strong_parameters in every controller to accept only the explicitly allowed fields.
“Treating every user input as potentially malicious is the basis of all application security. It is not paranoia, it is engineering.”
Secure authentication and session management in Rails
Authentication is your application's first line of defense. A fragile implementation compromises everything else, even if your business code is perfect.
Choosing the right authentication solution
Rails 8 introduces native authentication through rails generate authentication. For more complex projects, Devise remains the reference. The selection criteria:
- Devise: maturity, large community, available modules (confirmable, lockable, omniauthable)
- Rodauth: stricter on security, less implicit magic, recommended for critical apps
- Native Rails 8 auth: lightweight, ideal for greenfield projects without complex needs
- Authlogic: less maintained, to be avoided for new projects
Protecting passwords properly
Rails uses bcrypt through has_secure_password. It is solid. But configuration matters:
- bcrypt cost factor: minimum 12 in production (slows down brute-force attacks)
- Minimum length: require at least 12 characters in validations
- HaveIBeenPwned check:
pwnedgem to reject compromised passwords - Secure reset: single-use token, expired after 2 hours, invalidated after use
Securing cookies and sessions
The session cookie is a prime target. In config/initializers/session_store.rb, configure:
- HttpOnly: prevents JavaScript access to the cookie
- Secure: transmission over HTTPS only
- SameSite=Strict: reinforced protection against CSRF
- Short expiration: 30 minutes of inactivity in a sensitive context
Implementing two-factor authentication (2FA)
2FA reduces the risk of account compromise by 99%, even when a password has been stolen. The rotp gem handles TOTP codes compatible with Google Authenticator. Offer it as an option and make it mandatory for administrator roles.
Rails dependencies, configuration and security audit
Security is not just about application code. The gems you use, your server configuration and your audit processes are just as critical.
Keeping your gems up to date and watching CVEs
Every outdated gem is a potential vulnerability. In 2024, several critical vulnerabilities were discovered in popular gems. The essential habits:
- Bundler Audit:
bundle audit checkdetects gems with known CVEs - Dependabot: automates update PRs on GitHub
- Regular updates: schedule a dedicated monthly slot
- Gemfile.lock: always versioned to guarantee reproducibility
Configuring Rails in secure production mode
Several Rails settings are less strict in development. In production, check:
| Setting | Recommended value | Risk if misconfigured |
|---|---|---|
config.force_ssl | true | Data in clear text on the network |
config.log_level | :warn | Exposure of sensitive data in the logs |
config.filter_parameters | Include password, token, secret | Passwords logged in clear text |
SECRET_KEY_BASE | Environment variable, never hard-coded | Complete session hijacking |
| CORS | Explicit allowlist of origins | Unauthorized cross-origin requests |
Using Brakeman for static code audits
Brakeman is the reference tool for static security analysis in Rails. It scans your codebase and detects known vulnerabilities: XSS, SQL injection, disabled CSRF, mass assignment, etc. Integrate it into your CI/CD for immediate feedback on every commit. For an outside view, a Rails application security audit complements the tool with a manual review of authorizations and configuration.
Setting up HTTP security headers
HTTP security headers are an often neglected defensive layer. The secure_headers gem configures in one line: X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security (HSTS), and the CSP. Test your configuration on securityheaders.com. To go further on the performance and quality of your Rails application, read our guide on Ruby on Rails for shipping fast in 2026. If you would like a complete audit of your application, contact our Akolads team.
FAQ
Is Rails secure by default?
Rails includes solid native protections: CSRF token, automatic HTML escaping, strong parameters, and session encryption. These mechanisms cover the common cases.
But “secure by default” does not mean “secure without effort.” Every disabled protection, every misconfigured gem or every badly built SQL query creates a vulnerability. Regular code review and an audit with Brakeman remain essential.
How do you protect a Rails application against SQL injection?
The main protection comes from using ActiveRecord correctly: always pass user parameters through prepared methods (where(email: params[:email])) and never interpolate variables directly into SQL strings.
Complete this with strong_parameters to filter the allowed attributes, and run bundle audit check regularly to detect vulnerable gems.
Which gem should you use for authentication in Rails in 2026?
Three main options: Devise for projects with standard needs (email confirmation, account locking, OAuth), Rodauth for maximum security with less abstraction, and the native Rails 8 generator for simple projects.
For critical applications handling sensitive data, Rodauth is often recommended by security experts. Devise remains the most common choice for its maturity and its documentation.
How do you audit the security of a Ruby on Rails application?
Start by integrating Brakeman into your CI/CD pipeline: it automatically detects common vulnerabilities on every push. Use bundler-audit to check for gems with known CVEs.
For a more complete audit, call on a specialized provider who will carry out a penetration test (pentest) and a manual code review. Akolads can support you in this process: contact our team.
How much does security compliance cost for a Rails app?
The cost depends on the current state of your application. An initial audit with fixes for critical vulnerabilities generally represents between €1,500 and €5,000 for a mid-sized application.
Building security in from the start of development is much less expensive. Our article on Ruby on Rails development rates gives you a complete view of the budgets to plan for.