Google OAuth 2.0 authorization service implementation in .NET MAUI

jaymalli_programmer

Jay Malli

Posted on October 18, 2023

Google OAuth 2.0 authorization service implementation in .NET MAUI

Hello Programmers!, So today we'll learn that how to implement google OAuth 2.0 authorization service & integrate in .NET MAUI using WebView controls.

Step - 1 :

  • Create your Google Developer Account at Google Developer , if you han't any!

  • Open Cloud Console and click on DropDown menu then create on "New Project".

create new project

Step - 2 :

  • Go to "API & Services Tab by Clicking on menu icon of current project then Click on "Credentials".

Credentials

  • Click on "Create Credentials" Button and select "Oauth client ID" option.

Oauth Client ID

Step - 3 :

  • Select Application Type accroding to your requirement & provide Name.

App Info

  • Add redirect URI for app on which user is redirected after authorized.

    Redirect URI

  • Click on "Create Button"

  • Get the Client Id & Client Secrets.

Client Id & Secrets

STEP - 4 :

  • Setup basic maui App.
  • create authorization service & add below code.
namespace App
{
    public static class Auth
    {
        public static string ConstructGoogleSignInUrl()
        {
            // Specify the necessary parameters for the Google Sign-In URL
            const string clientId = "your_app_clientId";

            const string responseType = "code";
            const string accessType = "offline";
            const string redirect_uri = "your_app_redirect_uri";

            // Construct the Google Sign-In URL
            return "https://accounts.google.com/o/oauth2/v2/auth" +
                            $"?client_id={Uri.EscapeDataString(clientId)}" +
                            $"&redirect_uri={Uri.EscapeDataString(redirect_uri)}" +
                            $"&response_type={Uri.EscapeDataString(responseType)}" +
                            $"&scope={Uri.EscapeDataString(scope)}" +
                            $"&access_type={Uri.EscapeDataString(accessType)}" +
                            "&include_granted_scopes=true" +
                            "&prompt=consent";


        }


    }
}
Enter fullscreen mode Exit fullscreen mode

Step - 5 :

  • Load webview with the google login screen on button click.
private void OnGetFilesClicked(object sender, EventArgs e)
    {
        WebView _signInWebView = new WebView
        {
            Source = Auth.ConstructGoogleSignInUrl(),
            VerticalOptions = LayoutOptions.Fill,
        };

    }
ContentPage signInContentPage = new ContentPage
        {
            Content = grid,
        };

        try
        {
            Application.Current.MainPage.Navigation.PushModalAsync(signInContentPage);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
Enter fullscreen mode Exit fullscreen mode

Step - 6 :

  • The Google Login screen is visible after clicked on button. Fill the user email id & password, Click "Allow" button on oauth consent scrren.

Image description

  • you will get the code in the redirect URL if user authorized successfully.

Image description

Step - 7 :

  • Get access token from the code which was provided by URL after authorizing a user.

 public static (string, string) ExchangeCodeForAccessToken(string code)
        {

            // Configure the necessary parameters for the token exchange
            const string clientId = "your_app_client_id";
            const string clientSecret = "your_app_client_secret";
            const string redirectUri = "your_app_redirect_URI";

            // Create an instance of HttpClient
            using (HttpClient client = new HttpClient())
            {
                // Construct the token exchange URL
                const string tokenUrl = "https://oauth2.googleapis.com/token";

                // Create a FormUrlEncodedContent object with the required parameters
                FormUrlEncodedContent content = new FormUrlEncodedContent(new Dictionary<string, string>
              {
                   { "code", code },
                   { "client_id", clientId },
                   { "client_secret", clientSecret },
                   { "redirect_uri", redirectUri },
                   { "grant_type", "authorization_code" }
              });

                // Send a POST request to the token endpoint to exchange the code for an access token
                HttpResponseMessage response = client.PostAsync(tokenUrl, content).Result;

                // Check if the request was successful
                if (response.IsSuccessStatusCode)
                {
                    // Read the response content
                    string responseContent = response.Content.ReadAsStringAsync().Result;

                    // Parse the JSON response to extract the access token
                    JObject json = JObject.Parse(responseContent);
                    string accessToken = json.GetValue("access_token").ToString();
                    string refreshToken = json.GetValue("refresh_token").ToString();
                    return (accessToken, refreshToken);
                }
                else
                {
                    // Exception:  "Token exchange request failed with status code: {response.StatusCode}"
                }
            }

            return (null, null);
        }

Enter fullscreen mode Exit fullscreen mode
  • Get the access_token & refresh_token which is used to create credentials for access services API such as Drive , Gmail API etc.
// other code...

_signInWebView.Navigating += (sender, e) =>
       {

           string code = Auth.OnWebViewNavigating(e, signInContentPage);
           if (e.Url.StartsWith("http://localhost") && code != null)
           {

               (string access_token, string refresh_token) = Auth.ExchangeCodeForAccessToken(code);
           }

       };

Enter fullscreen mode Exit fullscreen mode

You can find the necessary code in the repository mentioned below.

GithHub Repository

Thank you for joining me on this journey of discovery and learning. If you found this blog post valuable and would like to connect further, I'd love to connect with you on LinkedIn. You can find me at LinkedIn

If you have thoughts, questions, or experiences related to this topic, please drop a comment below.

💖 💪 🙅 🚩
jaymalli_programmer
Jay Malli

Posted on October 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related