1

I am developing a Sinatra web app to which I plan to add a Google sign in capability.

While I am able to understand the Oauth2 authentication mechanism with Google and everything seems to work fine, I have a basic question on maintaining sessions. I am using the Server side web application flow of Oauth2.

Before I ask my question here is my understanding of the Oauth2 authentication mechanism.

Once the user clicks on the "Sign in with Google" button, the sequence of events are:

  • The user is redirected to the Google oauth authorization server.
  • The Google oauth2 authorization server checks if the user has a active session.
  • If yes it prompts the user to grant access to my application for the requested data from Google.
  • If the user grants access then the process of sending back an auth_code and getting access tokens commences.

Based on what I have encountered on the web, the code for all of the above would have to be put in a before filter.

My questions are below:

  1. If I add this code to a before filter, then there would be a round trip to the Google Authentication server for each request that comes to my application from the user.
  2. Am I thinking right in the statement 1 above?
  3. Is this necessary?
  4. Is there some other way of validating session without reaching out to the Google server for each request to my server?
  5. Will this not cause an overhead?
  6. How do web-apps using oauth2 typically handle checking session validity across multiple requests?

Sorry about the longish question and thanks for your patience.

ss_everywhere
  • 439
  • 7
  • 19

1 Answers1

1

When the user clicks on the Login link and returns with a valid response i.e request.env["omniauth.auth"], you need to store the "uid" in the session and then check for the session in the next requests. Like this

before do
  unless ['/login', '/auth/google_oauth2/callback'].include?(action)
    unless session[:uid]
      redirect "/login"
    end
  end
end

get "/auth/google_oauth2/callback" do
  session[:uid] = request.env["omniauth.auth"]["uid"]
  redirect "/"
end

Let me know if it works.

Noop
  • 26
  • 3
  • Thanks for your answer. I am not using Omniauth, just the Oauth2 gem. So the omniauth.auth hash wouldn't be available in request.env. But I understand that you are saying that I store some unique info from the user's profile in the session hash, and then check that in `before do`. My question is that, wouldn't this still allow the user to bypass `/login` even if he has logged out from google(provider) from another tab in the browser? – ss_everywhere Jun 03 '13 at 00:15
  • Accepting @Noop's answer as this pointed me in the right direction. – ss_everywhere Mar 12 '14 at 06:53