Authentication in web applications

Janko Marohnić edited this page May 18, 2012 · 9 revisions

Authentication in web applications

Here I want to show you how to make authentication in web applications. I will show you how to do it in Rails, but it can be easily applied to any other Rack-based framework, such as Sinatra or Padrino.

Let's suppose our index page is in the MainController.

# config/initializers/flickr.rb
require 'flickrie'
Flickrie.api_key = "your api key"
Flickrie.shared_secret = "your shared secret"
# config/routes.rb
class YourApp::Application.routes.draw do
  root :to => "main#index"
  get "", :to => "main#index"
  match "authenticate" => "main#authenticate"
end
# app/controllers/main_controller.rb
class MainController < ApplicationController
  def authenticate
    if params[:oauth_verifier].nil?
      request_token = Flickrie::OAuth.get_request_token \
        :callback_url => authenticate_url
      session[:request_token] = request_token.to_a
      redirect_to request_token.authorize_url
    else
      request_token = Flickrie::OAuth::RequestToken.new \
        *session.delete(:request_token)
      access_token = request_token.get_access_token(params[:oauth_verifier])
      session[:access_token] = access_token.to_a
      redirect_to :action => :index
    end
  end

  def index
    @flickr = Flickrie::Instance.new(*session[:access_token])
  end
end
# app/views/main/index.html.erb

<% @flickr.photos_from_set(24327094).each do |photo| %>
  <img src=<%= photo.source_url %> />

The controller part is kinda ugly, so I recommend you take a look at my flickr_auth gem, which does all of the controller action for you.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.