Free Support Forum - aspose.com

Get Authorization code (using c# code) for accessing gmail messages

Hi,

Can you share a sample application code (in C# class library) that gets the authorization code similar to the one that is got using using url below :

https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F

i have build a code that gets the auth code but that comes to be different than when the above url is hit.
sharing my code as below:

private string GetAuthCode()
{
string code = “”;

        // Creates a redirect URI using an available port on the loopback address.
        string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort());

        // Creates an HttpListener to listen for requests on that redirect URI.
        var http = new HttpListener();
        http.Prefixes.Add(redirectURI);
        http.Start();

        // Opens request in the browser.
        System.Diagnostics.Process.Start("https://accounts.google.com/o/oauth2/auth?redirect_uri=" + HttpUtility.UrlEncode("https://accounts.google.com/o/oauth2/approval/v2/approvalnativeapp") + "&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F");

        while (string.IsNullOrEmpty(code))
        {
            var context = http.GetContextAsync().Result;

            var response = context.Response;
            var responseOutput = response.OutputStream;
            http.Stop();
            
            code = context.Request.QueryString.Get("code");
        }
        return code;
    }

Thanks & Regards,

@anmolsdna

I suggest you to please visit this documentation link for your kind reference. If there is still an issue then please share feedback with us.