Search code examples
c#oauth-2.0google-apigoogle-oauthgoogle-workspace

Forcing user to sign in with their Google Organization (G Suite) account in mvc c#


I have implemented google authentication in my mvc site. Here is my sample code-

AuthConfig.cs

public static class AuthConfig
    {
        private static string GoogleClientId = ConfigurationManager.AppSettings["GoogleClientId"];
        private static string GoogleClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"];
        public static void RegisterAuth()
        {
            GoogleOAuth2Client clientGoog = new GoogleOAuth2Client(GoogleClientId, GoogleClientSecret);
            IDictionary<string, string> extraData = new Dictionary<string, string>();

            OpenAuth.AuthenticationClients.Add("google", () => clientGoog, extraData);
        }
    }

Global.asax

 AuthConfig.RegisterAuth();

AccountController.cs

public ActionResult RedirectToGoogle()
        {
            string provider = "google";
            string returnUrl = "";
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (ProviderName == null || ProviderName == "")
            {
                NameValueCollection nvs = Request.QueryString;
                if (nvs.Count > 0)
                {
                    if (nvs["state"] != null)
                    {
                        NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
                        if (provideritem["__provider__"] != null)
                        {
                            ProviderName = provideritem["__provider__"];
                        }
                    }
                }
            }

            GoogleOAuth2Client.RewriteRequest();

            var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
            var retUrl = returnUrl;
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            string ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);

            if (authResult.IsSuccessful)
            {
                string ProviderUserId = authResult.ProviderUserId;
            }

            return Redirect(Url.Action("Index", "User"));
        }

This code is working fine. But I want to restrict the user to sign-in with his/her organizational account like "[email protected]". Where I can specify the hosted domain property? When I created app id and secret for this app from google dev console, I saw Verify domain tab. Do I need to add my organizational domain here?


Solution

  • You can sort of. You can specify the hd (Hosted Domain) parameter within the Authentication URI parameters.

    hd - OPTIONAL - The hd (hosted domain) parameter streamlines the login process for G Suite hosted accounts. By including the domain of the G Suite user (for example, mycollege.edu), you can indicate that the account selection UI should be optimized for accounts at that domain. To optimize for G Suite accounts generally instead of just one domain, use an asterisk: hd=*.

    Don't rely on this UI optimization to control who can access your app, as client-side requests can be modified. Be sure to validate that the returned ID token has an hd claim value that matches what you expect (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is contained within a security token from Google, so the value can be trusted.