如何检索 facebook 用户信息 ASP.NET WEB API 2

how to retrieve facebook user info ASP.NET WEB API 2

我想注册一个用户,通过外部提供者(比如facebook),为了得到我需要的信息,我配置FacebookProvider如下

var options = new FacebookAuthenticationOptions {
    AppId = "***",
    AppSecret = "***",
    Scope = { "email" },
    Provider = new FacebookAuthenticationProvider {
        OnAuthenticated = (context) => {
            foreach (var x in context.User)
            {
                var claimType = string.Format("urn:facebook:{0}", x.Key);
                string claimValue = x.Value.ToString();
                if (!context.Identity.HasClaim(claimType, claimValue))
                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));
            }

            return Task.FromResult(0);
        }
    }
};

options.Fields.Add("id"); 
options.Fields.Add("name"); 
options.Fields.Add("email");

options.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalBearer;

app.UseFacebookAuthentication(options);

调试时在 OnAuthenticated 中,我看到了所有请求的字段,但是当我从邮递员调用 RegisterExternal 时,如下图

RegisterExternal call postman

GetExternalLoginInfoAsync returns 空

var info = await Authentication.GetExternalLoginInfoAsync();
if (info == null)
{
    return InternalServerError();
}

那么如何检索诸如电子邮件之类的查询字段?我认为所有必要的信息都存储在 cookie 中,但我如何将它们传输到服务器并提取 Identity 实例?

所有 nuget 包已更新到最新版本

p.s。我计划使用 iOS 应用程序

中的 API

我找到了解决方案。

更改ExternalLoginDataclass如下

private class ExternalLoginData
{
    ...
    // here added new field
    public IList<Claim> Claims { get; private set; }

    public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
    {
        ...
        return new ExternalLoginData
        {
            ...
            // here added claims setting
            Claims = identity.Claims.ToList()
        };
    }
}

更改ExternalLogin回调如下

public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
{
    ...
    if (hasRegistered)
    {
        ...
    }
    else
    {
        // here replaced getting claims by Claims field
        IEnumerable<Claim> claims = externalLogin.Claims;
        //IEnumerable<Claim> claims = externalLogin.GetClaims();
        ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
        Authentication.SignIn(identity);

    }

    return Ok();
}

因此,我们收到了不记名令牌。从中提取身份我们收到较早保存的声明。