ASP.NET C# MVC Core

ASP.NET Core 2.0 Google OAuth Redirection – 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 = "kerryritter.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;
        }
    };
});

Yep. That’s really it.

Leave a Reply

Your email address will not be published. Required fields are marked *