OpenID:尝试从Google OP获取电子邮件地址

35

我正在使用 dotnetopenauth 3.2 实现 Openid ,但是无法弄清楚如何让 Google 在 Claims Response 中传递电子邮件地址。 我知道 Google 不支持简单注册,但我无法确定他们支持什么。

需要说明的是,我刚开始学习 OpenID,我知道我对规范没有牢固的掌握,这可能导致我的困惑。

非常感谢任何帮助!

2个回答

52

好的,我已经弄清楚了。我在Google的联合登录API组上发布了一个问题,并被告知要使用属性交换

以下是DotNetOpenAuth的代码。

请不要在生产中使用此代码。这仅供说明目的!

请求:

using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
{
    IAuthenticationRequest request = openid.CreateRequest(openidurl);

    var fetch = new FetchRequest();
    fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
    request.AddExtension(fetch);

    // Send your visitor to their Provider for authentication.
    request.RedirectToProvider();
}

响应:

OpenIdRelyingParty openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response != null)
{
    switch (response.Status)
    {
        case AuthenticationStatus.Authenticated:
        {
            var fetch = response.GetExtension<FetchResponse>();
            string email = string.Empty();
            if (fetch != null)
            {
                email =  fetch.GetAttributeValue(
                    WellKnownAttributes.Contact.Email);
            }

            FormsAuthentication.RedirectFromLoginPage(
                response.ClaimedIdentifier, false);
            break;
        }
        ...
    }
}

我认为他在谈论的是提供者的实际友好名称,例如:"Google"、"Facebook",而无需解析响应。 - Brian
2
通过上述代码的帮助,您还可以获取用户的名字和姓氏 - 感谢zaffiro。 - Jags
获取(fetch)对我总是null,有什么想法为什么? - Shawn Mclean
你如何添加那些不是必需的可选属性呢? - shashwat
哦,我找到了... AddOptional - shashwat
显示剩余3条评论

1

当我尝试获取全名时,响应为空,请提供获取全名的解决方案, 这篇文章真的很有帮助。 谢谢。 我的示例代码如下。

var fetch = new FetchRequest();
            fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
            fetch.Attributes.AddRequired(WellKnownAttributes.Company.CompanyName);
            //fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);

            request.AddExtension(fetch);

if (fetch != null)
         {
             email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
             name = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
             company = fetch.GetAttributeValue(WellKnownAttributes.Company.CompanyName);
         } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接