Google OAuth 2.0 authorization service implementation in .NET MAUI
Tags: dotnet, csharp, oauth, api
Published: 2023-10-18 06:14:52

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](https://developers.google.com/)  , if you han't any!  

 - Open [Cloud Console](https://console.cloud.google.com/) and click on DropDown menu then create on "New Project".


![create new project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4n9qruel8wbk4esiu9l0.png)

Step - 2 :
 - Go to "API & Services Tab by Clicking on menu icon of current project then Click on "Credentials".

![Credentials](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qup7ct3840i66h9u8hr.png)

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

![Oauth Client ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yhvcai331zrv4kdw79pf.png)

Step - 3 : 
 - Select Application Type accroding to your requirement & provide Name.

![App Info](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmsoeeis20hxrcron0zt.png)

 - Add redirect URI for app on which user is redirected after authorized.   
![Redirect URI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4u8cbrkprj40h99igp7j.png)

 - Click on "Create Button"
 - Get the Client Id & Client Secrets.

![Client Id & Secrets](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/226geasdwykrd1mfjuha.png)

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";


        }


    }
}
```

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);
        }
```
  
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sado25jourmt6qslx6zc.png)



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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06qpmdvmr8jd3xjdagd0.png)

  
Step - 7 :
 - Get access token from the code which was provided by URL after authorizing a user.

- Add required nuget packages 
1) [Newtonsoft](https://www.nuget.org/packages/Newtonsoft.Json)

```
 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);
        }

```
  
- 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);
		   }

	   };

```

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

[GithHub Repository](https://github.com/JayMalli/Google_OAuth2.0-MAUI)

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](https://www.linkedin.com/in/jaymalli). You can find me at LinkedIn

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