yhara.jp

Recent Posts

Using bcrypt with Sinatra basic auth

2016-09-28
Tech

There is a guide for adding basic auth to your Sinatra app. Password is hardcoded in the short example, but in production, you may want a securer way.

bcrypt is the gem for you.

bcrypt

Add gem "bcrypt" to your Gemfile. (Don't confuse it with bcrypt-ruby gem, which is its former name)

Then you can generate a password hash like this:

require "bcrypt"
pass = BCrypt::Password.create("passw0rd")
puts pass  #=> $2a$10$fiCl.ng6uGr0ATcBi1OiA.KTvm2BlGdWWdBxdJqJ.mZMzKCoiSbc2

The result will be different each time you run, because bcrypt uses randomly generated salt.

Add this string to, say, your app's configuration file. Then you can check if user entered a correct password or not by using BCrypt::Password.new and is_password?.

correct_pass = BCrypt::Password.new("$2a$10$fiCl.ng6uGr0ATcBi1OiA.KTvm2BlGdWWdBxdJqJ.mZMzKCoiSbc2")
p correct_pass.is_password?("passw0rd")  #=> true

Example code

See the source of this blog for full example.

More posts

Posts

(more...)

Articles

(more...)

Category

Ads

About

About the author