Upgrade to Pro — share decks privately, control downloads, hide ads and more …

External User Authentication with OAuth and Rails

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

External User Authentication with OAuth and Rails

Talk for Omaha Emerging Developers' first meetup.

Alexandra Millatmal

May 10, 2016

Transcript

33 slides
  1. Why you might use external User Authentication • Customer experience

    • Leverage data from the external service @halfghaninNE
  2. OAuth • Protocol for authorizing a user for one site

    using their existing authentication on another • HTTP requests to a third-party API • Language-blind (a web app written in Rails can make the request of a site written in PHP) • Return tokens can be binary, JSON, or SAML @halfghaninNE
  3. Omniauth • Ruby "wrapper" for the OAuth process • Library

    that standardized multi-provider authentication • Facebook, GitHub, Twitter... even LinkedIn and Foursquare if that's your thing • List of services with Omniauth strategies @halfghaninNE
  4. Install your gem(s)! In your Gemfile gem 'omniauth-github' # or

    whatever provider you are using gem 'dotenv-rails' @halfghaninNE
  5. Initialize with your credentials In a new file, config/initializers/omniauth.rb Rails.application.config.middleware.use

    OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] end @halfghaninNE
  6. config/routes.rb (Remember that callback we provided to the third-party app

    registration? It goes here.) get '/auth/:provider/callback', to: 'sessions#create' @halfghaninNE
  7. sessions_controller.rb def create # render text: request.env['omniauth.auth'].to_yaml begin @user =

    User.from_omniauth(request.env['omniauth.auth']) session[:user_id] = @user.id flash[:success] = "Welcome, #{@user.name}!" rescue flash[:warning] = "There was an error :( " end redirect_to root_path end @halfghaninNE
  8. app/controllers/application_controller.rb private def current_user @current_user ||= User.find_by(id: session[:user_id]) end helper_method

    :current_user NOTE: helper_method is handy-dandy way that Rails makes this value available to our view files. @halfghaninNE
  9. app/views/layouts/application.html.erb <% if current_user %> <ul> <%= image_tag current_user.image_url, alt:

    current_user.name %> <li><%= link_to 'Log Out', logout_path, method: :delete %></li> </ul> <% else %> <li><%= link_to 'Login with GitHub', '/auth/github' %></li> <% end %> NOTE: Rails RESTful routing is helping us out here. @halfghaninNE
  10. config/routes.rb delete '/logout', to: 'sessions#destroy' sessions_controller.rb def destroy if current_user

    session.delete(:user_id) flash[:success] = 'See you!' end redirect_to root_path end @halfghaninNE

More Decks by Alexandra Millatmal

Other Decks in Technology