Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and Google OAuth2 redirect_uri

I'm trying to create a simple application using AngularJS and Google's OAuth2 for authentication.

Due to popup-blocking issues, and mobile friendliness, I decided I wouldn't use the Google APIs Client Library for JavaScript.

This left me with the option of doing a full redirect to the OAuth2 endpoint at google, and redirect users back to my app with the access_token.

I thought this would work just fine. The redirect URI would be 'http://myapp.com/#/register' with an appended 'access_token' query parameter. I would then consume the access_token and direct the user to somewhere else in my app.

This didn't work, as the Google API credentials (http://developers.google.com/console) don't like having a '#' in the Redirect URI's.

I then tried turning off the '#' requirement in URI's by using

$locationProvider.html5Mode(true);

This didn't work either, because explicitly browsing (in Chrome) to 'http://myapp.com/register' is not recognised by my Angular routes.

Any thoughts on how I should acheive this?

like image 590
mortware Avatar asked Jan 12 '14 19:01

mortware


People also ask

What is the purpose of Redirect_uri?

A redirect URI, or reply URL, is the location where the authorization server sends the user once the app has been successfully authorized and granted an authorization code or access token.

How does Google OAuth work?

OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives. This OAuth 2.0 flow is called the implicit grant flow.

What should be included in Authorized JavaScript origins?

In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains. You cannot use wildcards. In the example below, the second URL could be a production URL.


1 Answers

The following worked for me, with html5 mode set to true in my app.

This code goes into your controller for the redirect page (make sure to inject the $window service):

//Get parameters from hash fragment
var params = {};
if ($window.location.hash.indexOf('#') === 0) {
    var regex = /([^&=]+)=([^&]*)/g, m;
    while (m = regex.exec($window.location.hash.substr(1))) {
        params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
}

//Validate params, store access token etc.
if (!params.access_token) {
    //...
}

If your app doesn't recognise the non-# routes, make sure that your server has the rewrite engine enabled and that you redirect all relevant requests to your angular app main HTML file.

like image 156
Adam Reis Avatar answered Oct 17 '22 15:10

Adam Reis