如何使用asp.net mvc facebook访问用户的电子邮件地址?

3

我正在使用这个链接作为起点,因为我对Asp.net MVC还很陌生。

我已经能够获取Facebook用户的数据我应该使用哪些权限来获取用户的电子邮件地址以及在哪里获取?

dynamic me = client.Get("me");
if (response.ContainsKey("verified"))
{
    facebookVerified = response["verified"];
}
else
{
    facebookVerified = false;
}
db.ExternalUsers.Add(new ExternalUserInformation
{
     UserId = newUser.UserId,
     FullName = me.name,
     Link = me.link,
     Email = model.Email, // Want the Email ID from Facebook
     Gender = me.gender,
     Verified = facebookVerified
});

登录代码:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
        return RedirectToLocal(returnUrl);
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}

1
这应该能回答你的问题:https://dev59.com/p2jWa4cB1Zd3GeqPvOiE#13125765 - Sven Grosen
你的问题解决了吗?如果是,麻烦写下正确的答案并接受它。 - Sahil Mittal
还没有解决。 - vini
请展示您所使用的登录代码。 - Sahil Mittal
已解决问题。 - vini
很好。你可以在这里分享你的答案并接受它,也可以给出悬赏,否则悬赏将被浪费! :) - Sahil Mittal
1个回答

10
你在这里缺少的是从Facebook获取电子邮件地址的额外权限。
请查看以下两个屏幕截图,第二个屏幕截图请求额外信息,包括电子邮件地址。
基本权限

enter image description here

更多权限

enter image description here

为了做到这一点,您需要将此附加的必需信息作为“范围”提供。

我今天写了一个小教程,介绍如何使用Facebook登录,可以在这里阅读 - 使用Facebook登录与ASP.NET MVC 4。这将回答您大部分的问题。

对于您的问题,以下是您应该执行的操作:

创建一个FacebookScopedClient类(以下是代码),然后在您的AuthConfig.cs中像这样使用它

var facebooksocialData = new Dictionary<string, object>();
facebooksocialData.Add("scope", "email, publish_stream, read_stream");

OAuthWebSecurity.RegisterClient(new FacebookScopedClient(
    appId: "xxxxxxxx",
    appSecret: "xxxxxxxxxxxxxxxxxxx",
    scope:"email, user_likes, friends_likes, user_birthday),
    "Facebook",
    null
);

FacebookScopedClient类的代码 -

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.AspNet;
using Newtonsoft.Json;

public class FacebookScopedClient : IAuthenticationClient
{
    private string appId;
    private string appSecret;
    private string scope;

    private const string baseUrl = "https://www.facebook.com/dialog/oauth?client_id=";
    public const string graphApiToken = "https://graph.facebook.com/oauth/access_token?";
    public const string graphApiMe = "https://graph.facebook.com/me?";

    private static string GetHTML(string URL)
    {
        string connectionString = URL;

        try
        {
            System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
            myRequest.Credentials = CredentialCache.DefaultCredentials;
            //// Get the response
            WebResponse webResponse = myRequest.GetResponse();
            Stream respStream = webResponse.GetResponseStream();
            ////
            StreamReader ioStream = new StreamReader(respStream);
            string pageContent = ioStream.ReadToEnd();
            //// Close streams
            ioStream.Close();
            respStream.Close();
            return pageContent;
        }
        catch (Exception)
        {
        }
        return null;
    }

    private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
    {
        string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);
        if (token == null || token == "")
        {
            return null;
        }
        string access_token = token.Substring(token.IndexOf("access_token="), token.IndexOf("&"));
        string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);

        // this dictionary must contains
        Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
        return userData;
    }

    public FacebookScopedClient(string appId, string appSecret, string scope)
    {
        this.appId = appId;
        this.appSecret = appSecret;
        this.scope = scope;
    }

    public string ProviderName
    {
        get { return "Facebook"; }
    }

    public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
    {
        string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + scope;
        context.Response.Redirect(url);
    }

    public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
    {
        string code = context.Request.QueryString["code"];

        string rawUrl = context.Request.Url.OriginalString;
        //From this we need to remove code portion
        rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

        IDictionary<string, string> userData = GetUserData(code, rawUrl);

        if (userData == null)
            return new AuthenticationResult(false, ProviderName, null, null, null);

        string id = userData["id"];
        string username = userData["username"];
        userData.Remove("id");
        userData.Remove("username");

        AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
        return result;
    }
}

参考资料:


仅供参考,我遇到的问题。首先,在这一行“scope:email,user_likes,friends_likes,user_birthday)”中,缺少一个引号"。现在最重要的是,新版Facebook API已经弃用了username,这将导致异常,因为没有数据将被返回。所以从这一行中删除username:string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);并且由于我们没有收到它,所以我将string username = userData["username"];更改为string username = userData["name"];并删除此行:userData.Remove("username");**干杯 - Zia Ul Rehman Mughal

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