OAuthWebSecurity 与 Facebook 未按预期使用电子邮件权限 [英] OAuthWebSecurity with Facebook not using email permission as expected

查看:14
本文介绍了OAuthWebSecurity 与 Facebook 未按预期使用电子邮件权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的 OAuthWebSecurity 对 Facebook 进行身份验证,我在我的 Facebook 应用程序中添加了电子邮件权限.现在,正如我所读到的,我需要定义一个范围才能在结果中实际获取电子邮件.到目前为止,没有范围,我没有收到用户的电子邮件,也不知道为什么,因为我看不到在哪里定义范围".

Using the new OAuthWebSecurity for authenticating with Facebook, I added the email permission on my Facebook application. Now, as I can read, I need to define a scope to be able to actually get the email in the result. So far without the scope I'm not getting the users' email and am not sure why as I can not see where to define the "scope".

这只是 ASP.NET MVC 4 默认身份验证控制器外部登录的翻版.

It's just a rip of the ASP.NET MVC 4 default authenticationcontrollers external login.

推荐答案

首先,extraData 参数没有传递给 facebook.它仅供内部使用.请参阅以下链接,了解如何在您的网站上使用这些数据:

Firstly, the extraData parameter is not passed to facebook. It is for internal use only. See the following link on how this data can be used on your site:

http://blogs.msdn.com/b/pranav_rastogi/archive/2012/08/24/customizing-the-login-ui-when-using-oauth-openid.aspx

现在,到肉:

除了OAuthWebSecurity中的RegisterFacebookClientRegisterYahooClient等方法,还有一个通用方法RegisterClient>.这是我们将用于此解决方案的方法.

In addition to the methods RegisterFacebookClient, RegisterYahooClient etc. in OAuthWebSecurity, there is also a generic method RegisterClient. This is the method we will be using for this solution.

这个想法源于以下提供的代码:http://mvc4beginner.com/Sample-Code/Facebook-Twitter/MVC-4-oAuth-Facebook-Login-EMail-Problem-Solved.html

This idea germinates from the code provided at: http://mvc4beginner.com/Sample-Code/Facebook-Twitter/MVC-4-oAuth-Facebook-Login-EMail-Problem-Solved.html

但是,我们不会使用解决方案提供的骇人听闻的方法.相反,我们将创建一个名为 FacebookScopedClient 的新类,它将实现 IAuthenticationClient.然后我们将简单地使用以下方法注册该类:

However, we will not be using the hacky approach provided by the solution. Instead, we will create a new class called FacebookScopedClient which will implement IAuthenticationClient. Then we will simply register the class using:

OAuthWebSecurity.RegisterClient(new FacebookScopedClient("your_app_id", "your_app_secret"), "Facebook", null);

在 AuthConfig.cs 中

in AuthConfig.cs

类的代码是:

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

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

            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 data = GetHTML(graphApiMe + "fields=id,name,email,gender,link&access_token=" + token.Substring("access_token=", "&"));

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

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

            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=email";
                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["email"];
                userData.Remove("id");
                userData.Remove("email");

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

现在在

public ActionResult ExternalLoginCallback(string returnUrl)

AccountController 中的方法,result.ExtraData 应该有电子邮件.

method in AccountController, result.ExtraData should have the email.

我错过了这篇文章中的一些代码.我在下面添加它:

public static class String
    {
        public static string Substring(this string str, string StartString, string EndString)
        {
            if (str.Contains(StartString))
            {
                int iStart = str.IndexOf(StartString) + StartString.Length;
                int iEnd = str.IndexOf(EndString, iStart);
                return str.Substring(iStart, (iEnd - iStart));
            }
            return null;
        }
    }

干杯!

这篇关于OAuthWebSecurity 与 Facebook 未按预期使用电子邮件权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆