DEV Community

stuxnat
stuxnat

Posted on • Edited on

Rails App Security

Security is an important aspect to consider when building web applications. There are many layers to keep in mind when thinking about app security, such as the back-end storage, the web server, and the client-facing component.

Below are some things you can do to ensure that you build a more secure Rail app:

1. Proper CORS configuration
One important thing to do with CORS to prevent unwanted access is to define access within your APIs correctly. The example below uses the wildcard '*' allows access from any origin and gives access to any resources - typically, this is not advisable (it depends on the purpose of your API). Instead, you can define which origins are allowed to access your API.

This is an example of an unsecure CORS configuration:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end
Enter fullscreen mode Exit fullscreen mode

To define permitted origins and limit access, you can do something like this:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000'
    resource '*', headers: :any, methods: [:get]
  end
end
Enter fullscreen mode Exit fullscreen mode

2. Authentication and Access Controls
It is crucial to verify user identity to prevent unauthorized access. You can use the Devise gem for user management.

Another important thing to do is maintain control to CREATE, READ, UPDATE, DESTROY actions. It is important to reinforce ownership of records made by users so that users can modify only permitted records. Pundit is a great tool you can use to create user control policies.

3. Sessions Security
You can avoid common hijacking situations by managing sessions. Implementing reset_session in your code prevents an attacker from using a fixed session to gain unauthorized access by issuing a new session identifier after a successful login.

Other things to keep in mind when using sessions: use HTTPS to prevent session theft, and do not store permanent data in sessions - store permanent data in the database.

A great resource to use is Open Web Application Security Project (OSWAP). OWASP Top Ten lists the ten most common security vulnerabilities and how to address them.

Top comments (0)