ASP.NET Core 2.0 Google OAuth Redirection with Add Hosted Domain and other parameters
💻 coding

ASP.NET Core 2.0 Google OAuth Redirection with Add Hosted Domain and other parameters

1 min read 107 words
1 min read
ShareWhatsAppPost on X
  • 1To add a hosted domain parameter in Google OAuth, modify the Events parameter in Startup.cs.
  • 2Set the hosted domain in the OnRedirectToAuthorizationEndpoint method to redirect users correctly.
  • 3Ensure users have the correct domain by validating it in the OnCreatingTicket method.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To add a hosted domain parameter in Google OAuth, modify the Events parameter in Startup.cs."

ASP.NET Core 2.0 Google OAuth Redirection with Add Hosted Domain and other parameters

Adding a hosted domain parameter is not directly supposed through the GoogleOptions class, unfortunately – however with a few (not obvious) tweaks, you can easily add the parameter!

In your Startup.cs, set up a new Events parameter as such:

services.AddAuthentication().AddGoogle(googleOptions =>
{
 const string hostedDomain = "askgif.com";

 googleOptions.ClientId = Configuration["Google:ClientId"];
 googleOptions.ClientSecret = Configuration["Google:ClientSecret"];
 googleOptions.Events = new OAuthEvents
 {
 OnRedirectToAuthorizationEndpoint = context =>
 {
 context.Response.Redirect(context.RedirectUri + "&hd=" + System.Net.WebUtility.UrlEncode(hostedDomain));

 return Task.CompletedTask;
 },
 OnCreatingTicket = context =>
 {
 if (context.User.Value("domain") != hostedDomain)
 {
 throw new AuthenticationException($"You must sign in with a {hostedDomain} email address");
 }

 return Task.CompletedTask;
 }
 };
});

It's as simple as it is explained above. :)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 20 March 2019 · 1 min read · 107 words

Part of AskGif Blog · coding

You might also like