Sunday, October 8, 2017

C#: Running Google OAuth 2.0 for Desktop Apps on Windows 7

This article demonstrates the code required to make Google OAuth 2.0  for Windows desktop applications work with Windows 7.

Google OAuth 2.0 means that an application can relying on Google's user credentials in order to support authentication. The users of an application can use their GMail address and corresponding password to login to a non-Google application. In order to implement OAuth 2.0 support, there are variety of steps that must be taken from an application registration process and a development standpoint.  Google has created extremely comprehensive documentation with regards to supporting this authentication protocol, "OAuth 2.0 for Mobile & Desktop Apps" and has also provided series of examples on,, that target a variety of Windows desktop configurations. The problem with the Windows desktop samples provided is that they fail on Windows 7.

The solution from example Windows console application from the aforementioned, URI appears as follows in Visual Studio's Solution Explorer:

When this applications run on Windows 7 an exception is thrown and an "Access is denied" error message is displayed:

The specific line at which exception is thrown is line 78 in the following screenshot (the Start method of an instance of the HttpListener class):

The mechanism used to fix the Access Denied error is to "Reserves the specified URL for non-administrator users and accounts" (see "add urlacl") by means of the netsh command with the http add urlacl arguments. Basically this means, the user has permission to create an HttpListener instance and to listen on the URl by invoking HttpListener.Start. In invoking netsh to facilitate URL access is handled by the Process class's (see the System.Diagnostics namespace) Start method. An example of invoking netsh using Process.Start to allow a user to access a specific URL is show as follows:

public static void EnableAccessOnWindows7(string url)
    string domain = Environment.UserDomainName;
    string user = Environment.UserName;
    string commandArgs = 
             $"http add urlacl url={url} user={domain}\\{user}";
    ProcessStartInfo startInfo = 
             new ProcessStartInfo("netsh", commandArgs);

    startInfo.Verb = "runas";
    startInfo.CreateNoWindow = true;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.UseShellExecute = true;

The EnableAccessOnWindows7 method is invoked by Google OAuth 2.0 Console Application sample at line 68 to allow the sample to run on Windows 7:

Given the changes made the sample now runs on Windows 7.

Source Code

Normally source code for these posts is made available through Google owns the sample reference and maintains a master copy in their own repository: The code associated with the modifications required to allow the desktop samples to run on windows 7 are included in the body of this post.

No comments :

Post a Comment