Mugu
Mugu

Reputation: 133

Getting OAuth access token for Google Plus API

I m current developing an app for google plus. I want to fetch the access token from google plus API. I want to use OAuth 2.0 to fetch the access token. I have constructed to URL

"https://accounts.google.com/o/oauth2/auth?client_id=752264386186- 72f3ef2ok1j3k8g12h7hg8k5kjt9s9si.apps.googleusercontent.com&scope=https: //www.googleapis.com/auth/plus.me&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code"

which when I pasted to by browser asks to sign in with my google account. So when I enter my credentials it asks for "allow access" or "no thanks" . when I click "allow access" it gives me the access token in my browser. I want the above steps to be done using my C# code.

How I can navigate to authorisation page from code and fetch the access token once the authentication is sucessful. Should I use httpwebrequest or webclient or rest sharp. Please provide me some sample code also.

Upvotes: 1

Views: 2572

Answers (2)

user1239234
user1239234

Reputation: 63

This code is EPIC, literally amazing.

Upvotes: 0

Sami Rajala
Sami Rajala

Reputation: 191

If using the WebBrowser is okay for you, here is a simple example how I did the same thing with Foursquare API. This code has been written only to test how it goes, so I'm sure it's missing several important things like error handling etc.

 private void button1_Click(object sender, RoutedEventArgs e)
    {
        string address =
            "https://foursquare.com/oauth2/authenticate" +
            "?client_id=" + CLIENT_ID +
            "&response_type=token" +
            "&redirect_uri=" + CALLBACK_URI;
        webBrowser1.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser1_Navigated);
        webBrowser1.Navigate(new Uri(address, UriKind.Absolute));
    }

    void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        response = e.Uri.ToString();
        System.Diagnostics.Debug.WriteLine(e.Uri.ToString());
        if (response.LastIndexOf("access_token=") != -1)
        {
            string token = response.Substring(response.LastIndexOf("#access_token=") + "#access_token=".Length);
            System.Diagnostics.Debug.WriteLine("TOKEN: " + token);
        }
    }

Once you have allowed access, you end up getting the callback URI with the access_token. Note that webBrowser1_Navigated might get called several (each time you are navigating to another page in the embedded web browser).

Upvotes: 1

Related Questions