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".
Step - 2 :
- Go to "API & Services Tab by Clicking on menu icon of current project then Click on "Credentials".
- Click on "Create Credentials" Button and select "Oauth client ID" option.
Step - 3 :
- Select Application Type accroding to your requirement & provide Name.
Add redirect URI for app on which user is redirected after authorized.
Click on "Create Button"
Get the Client Id & Client 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";
}
}
}
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.
- you will get the code in the redirect URL if user authorized successfully.
Step - 7 :
-
Get access token from the code which was provided by URL after authorizing a user.
- Add required nuget packages 1) Newtonsoft
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.
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.
Top comments (2)
@mpasdanis Did you ever manage to make it work on Android and IOS? Been trying to login a user using google and getting their photos. Tried WebAuthenticator but keeep getting
{System.InvalidOperationException: You must subclass the WebAuthenticatorCallbackActivity and create an IntentFilter for it which matches your callbackUrl. at Microsoft.Maui.Authentication.WebAuthenticatorImplementation.AuthenticateAsync(WebAuthenticatorOptions webAuthenticatorOptions) in /_/src/Essentials/src/WebAuthenticator/WebAuthenticator.android.cs:line 66
After testing it...this can only be applied only in desktop application because google in mobile apps doesn't allow auth2.0 authentication via webview for security reasons.