How to integrate OAuth with a single page application?

Golo Roden picture Golo Roden · Jan 30, 2014 · Viewed 24.1k times · Source

When using OAuth (2) I need a redirection endpoint in my application that the OAuth-offering service can redirect to, once I have been authenticated.

How do I handle this in a single page application? Of course, a redirect to the OAuth-offering service is not nice here, and it may not even be possible to redirect back.

I know that OAuth also supports a username / password based token generation. This works perfectly with an AJAX call, but requires my single page application to ask for a username and password.

How do you usually handle this?

Answer

José F. Romaniello picture José F. Romaniello · Jan 31, 2014

Most of the time, a redirect is okay even for SPA because users don't like to put their X service credentials on any other website than X. An alternative will be to use an small popup window, you can check what Discourse does. IMHO a redirect is better than a popup.

Google Some providers support the resource owner flow which is what you described as sending username and password, but this is not nice. These are the problems I see:

  1. Asking google credentials to users in your site will be a no-go for some users.
  2. The resource owner flows need the client_secret too and this is something that you must NOT put in your client side javascript. If you instantiate the resource owner flow from your server-side application and your application is not in the same geographically region than the user, the user will get a warning "hey someone is trying to access with your credentials from India".

OAuth describes a client-side flow called implicit flow. Using this flow you don't need any interaction in your server-side and you don't need the client_secret. The OAuth provider redirects to your application with a "#access_token=xx". It is called implicit because you don't need to exchange authorization code per access token, you get an access_token directly.

Google implement the implicit flow, check: Using OAuth2 for Client-Side apps.

If you want to use the implicit flow with some provider that doesn't support it like Github, you can use an authentication broker like Auth0.

disclaimer: I work for Auth0.