Protect Your Database IDs in Rails with UUID
For most backend developers, protecting the database from hackers is at the top of the priority list. All it takes is one bad actor getting access to information they shouldn’t have, and you’re screwed.
In SQL databases, one potential vulnerability is the fact that in many databases, the primary key, or ID, for each data entry is just an integer that increments by 1. So if a hacker wants to access some random record, they can just try random integers and see what happens.
UUID, which generates random strings of letters and numbers, is a great way to prevent that problem. Instead of using simple integers that increase by 1 each time, your database IDs look more like this:
"0e212515–68b0–41b8–880a-fa4a9d818af6"
"27279e0a-dbaf-4b67–8323–0260193e5a92"
"311ca64f-1f1e-4360–8ae4–8dff9df1f2da"
Much harder to guess.
So if you’re looking for some peace of mind, here’s how to get UUID primary keys up and running with a Rails backend and a PostgreSQL database.
If you haven’t yet, first start your new project on the command line with rails new my-app -d=postgresql
, replacing my-app with the project name of your choice.
Next, before you create any other migrations, type rails g migration enable_uuid
in the command line. That should add a new migration file to the db/migrate
folder.
In that new file, under def change, add enable_extension 'pgcrypto'
.
Then, to actually use UUID strings for your primary keys, go to config/initializers
and create a generators.rb
file if you don’t already have one. Then type:
Rails.application.config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
Now you’re ready to generate any future migrations and models you might need! Create them the way you normally would, and their IDs will automatically be formatted as UUIDs.
And you can breathe just a tiny bit easier knowing that your primary keys are now much harder to guess.