Web Authentication Review — part one
I want to refresh my memory on web authentication so I decide to write a litter review about different authentication method and how to implement them in Rails.
The easiest one is the http basic authentication method. The idea is user input their credentials on client side. The information will be send to the server and the server verify the information and grant access if the credentials are correct. Sounds easy but not so safe. So how do we make it safe?
Let’s consider how credentials can be send from client side to the server. There are two ways: 1. includes credentials in the url that you are sending, as query parameters. 2. includes credentials in your request header.
Obviously, the second way is our preferred method. But still, we don’t want our credentials visible, since request header can be easily obtained.
Let’s concat our credentials into one string that looks like “username:password” and encode our credentials with Base64.
Now, in your request header, includes a key/value pair:
The server will know that you would like to authentic with Http basic and decode you credential.
However, Base64 is not a strong encoding method. Your credentials are as good as gone if someone obtained the encoded string. So we need to make sure others can’t sniff around your internet conversation by using ssl.
If we put everything together, here is how the code looks like:
If more complicated authenticate logic needed we can use rails helper
atuhenticate_or_request_with_http_basic like this:
class UserController < ApplicationController
authenticate_or_request_with_http_basic('Administration') do |username, password|
Keep these things in mind when using http basic authentication
- You are including your credentials in each request.
- You can’t log out
- You can’t expire credentials
Imagine you are implementing authentication for your RESFful Api. With our current implementation, we need to authenticate with user credential on each request since they are stateless. It’s not a great user experience and it not safe either, since some request may be accidentally send to url without ssl enforced. In such case, a token is used to identify users after they signed in. We generate a unique(uuid is a good method) temporary credential that expires over time. Such temporary credentials are usually called Api Key.
Now, instead of authenticate with username and password, we can authenticate with Api keys (or Api key ID plus Api Key Secret).