我已在我的mvc网站中实施了Google身份验证。这是我的示例代码 -
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"));
}
此代码工作正常。但我想限制用户使用他/她的组织帐户登录,例如"abc@example.com"
。我可以在哪里指定托管域属性?当我从google开发者控制台为此应用创建应用ID和密码时,我看到了Verify domain
标签。我需要在此处添加我的组织域吗?
答案 0 :(得分:0)
你可以。您可以在Authentication URI参数中指定hd(Hosted Domain)参数。
hd - OPTIONAL - hd(托管域)参数简化了G Suite托管帐户的登录过程。通过包含G Suite用户的域(例如,mycollege.edu),您可以指明应针对该域的帐户优化帐户选择UI。要优化G Suite帐户而不是仅针对一个域,请使用星号:hd = *。
不要依赖此UI 优化来控制谁可以访问您的应用,因为可以修改客户端请求。请务必验证返回的ID令牌的hd声明值是否与您期望的一致(例如mycolledge.edu)。与请求参数不同,ID令牌声明包含在Google的安全令牌中,因此可以信任该值。