samy
samy

Reputation: 1969

Google OAuth 2.0 on WinForm

I need some directions because I'm pretty lost. I'm working on a very small app in WinForms and, it uses Google API's. to be able to get to user data I need to get his user name and password, up to this part every thing works but, I don't have any save user ability.

Now, I don't want to ask the user's name and password every time, so I'm trying to find a safe way to do that.

I asked a question about where should I put this info, and got the answer that it is not good idea to save username and passwords, and I should use Google OAuth 2.0 instead.

But, my problem is that I need to use a web browser for Google OAuth 2.0, and now I'm not sure how to implement this in my WinForm app.

My Questions:

  1. Is it possible to get data from the a web browser to my app?
  2. Should I look for a different way to get user data? (any suggestion will be great).

Upvotes: 3

Views: 10524

Answers (5)

Jeff Tasi
Jeff Tasi

Reputation: 1

It looks like you're encountering issues with OAuth2 login using the WebBrowser control in your WinForms application. I am the author of the Bee.OAuth2.WinForms package, which is designed to simplify OAuth2 integration with Google and other providers. It handles the OAuth2 flow and provides a seamless way to integrate authentication into your WinForms application.

You can install the package from NuGet and refer to the documentation for setup instructions. Here’s a basic example of how to use it:

https://www.nuget.org/packages/Bee.OAuth2.WinForms

var options = new TGoogleOAuthOptions()
{
    ClientId = "your-client-id",
    ClientSecret = "your-client-secret",
    RedirectUri = "http://localhost:5000/callback",
    UsePKCE = true
};
var client = new TOAuthClient(options);

// Open the login interface, let the user sign in, and retrieve user information after authentication.
var result = await client.Login();  
var userinfo = $"UserID : {result.UserInfo.UserId}\r\n" +
               $"UserName : {result.UserInfo.UserName}\r\n" +
               $"Email : {result.UserInfo.Email}\r\n" +
               $"RawJson : \r\n{result.UserInfo.RawJson}";

Upvotes: 0

Mario Favere
Mario Favere

Reputation: 519

here is a sample code to get user's mail (and some basic information). You can save this e.g. in the program-settings or do whatever you want with it.

using System;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using System.Threading;
using Google.Apis.Auth.OAuth2;

    public class GoogleUserOutputData
    {
        public string id { get; set; }
        public string name { get; set; }
        public string given_name { get; set; }
        public string email { get; set; }
        public string picture { get; set; }
    }
    static string[] Scopes = { "https://www.googleapis.com/auth/userinfo.email" };
    // conversie stream <=> string : https://www.csharp411.com/c-convert-string-to-stream-and-stream-to-string/
    private static string Secrets = "your streamdata - converted with code from the above site, from the json-file you got from Google";

    public static string GoogleLogin()
    {
        try
        {
            byte[] ByteArray = Encoding.ASCII.GetBytes(Secrets);
            GoogleClientSecrets GSecrets = GoogleClientSecrets.FromStream(new MemoryStream(ByteArray));
            UserCredential UserCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(GSecrets.Secrets, Scopes, "user", CancellationToken.None).Result;

            HttpClient client = new HttpClient();
            var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + UserCredentials.Token.AccessToken;
            HttpResponseMessage output = client.GetAsync(urlProfile).Result;
            GoogleUserOutputData userdata = null;
            if (output.IsSuccessStatusCode)
            {
                string outputData = output.Content.ReadAsStringAsync().Result;
                userdata = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
            }

            if (userdata != null)
                return userdata.email;
            else return "";
        }
        catch (Exception Exception)
        {
            return "";
        }
    }

Upvotes: 0

David Primmer
David Primmer

Reputation: 421

Two most important pieces of info for you to know are that you should use a client library to do the work for you, and you should use the "Installed application" flow/client type.

Use the tutorial here, which walks you through using an installed application: https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted

You do have to use a web browser to get the credentials from the user, but once you do that, you should be able to re-use those credentials (refresh token) without re-prompting. The library makes moving these credentials from the browser to your app simple.

Upvotes: 2

Yusubov
Yusubov

Reputation: 5843

In short: You have to focus your attention in OAuth 2.0 in the client library.

Thus, the documentation has very good descriptions and samples that you need to process with.

While some services do not require authentication at all, or only use your developer key, most of the services require access to some of the users data. The authentication model used to access user data is OAuth2.0.

Reference for the source - google-api-dotnet-client OAuth2.0

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

Performing OAuth2 in non-browser application is known as "2-legged OAuth2".

Server-side, 3-legged OAuth2 is for browser authentication. It consist of following steps:

  1. the application navigates to your web app
  2. your web app redirects to the OAuth2 endpoint in Google with correct get parameters
  3. Google authenticates your user and redirects the browser back to your web app with user token
  4. your web app uses the token to connect to Google services

Client-side, 2-legged OAuth2 consist in hosting the WebBrowser control in your application and following steps 2-3 of 3-legged authentication:

  1. the web browser control goes to OAuth2 endpoint in Google pretending your web app is going to be authenticated
  2. the web browser control allows user to authenticate and redirects back to your web app
  3. but you don't really even have any web app - upon redirecting back to your application, you catch the redirect event of the web browser control and extract the authentication token

Having the user token, the winforms app connects to Google services on behalf of the user.

Upvotes: 1

Related Questions