2

我的目标是使用 FB 登录按钮,以便 FB 用户可以登录到我的 ASP.NET MVC 3 网站。Facebook C# SDK 最近似乎发生了一些变化,所有旧示例都不适用于新版本。我已经尝试了一天让它们工作......我正在完成教程开始使用 Facebook C# SDK for ASP.NET

目前,当我浏览它时,http://localhost:8033/它似乎会自动让我登录(即使在重新启动 Chrome 之后),因为它显示“ my-name uses my-app-name ”并显示我的图片。我希望它改为显示一个 FB 登录按钮。当我去时,http://localhost:8033/Home/About我得到一个Session["AccessToken"]空错误(这是有道理的,因为它显然没有被设置)。

这是我所拥有的:

家庭控制器.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;

namespace FacebookTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            var accessToken = Session["AccessToken"].ToString();
            var client = new FacebookClient(accessToken);
            dynamic result = client.Get("me", new { fields = "name,id" });
            string name = result.name;
            string id = result.id;

            ViewBag.Message = "Hello id: " + id;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FacebookLogin(HttpContext context)
        {
            var accessToken = context.Request["accessToken"];
            context.Session["AccessToken"] = accessToken;

            return RedirectToAction("About");
        }
    }
}

索引.cshtml

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            //appId: 'YOUR_APP_ID', // App ID
            appId: '<MY-NUMBER-REMOVED>', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        // Additional initialization code here
        FB.Event.subscribe('auth.authResponseChange', function (response) {
            if (response.status === 'connected') {
                // the user is logged in and has authenticated your
                // app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed
                // request, and the time the access token 
                // and signed request each expire
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;

                // TODO: Handle the access token
                // Do a post to the server to finish the logon
                // This is a form post since we don't want to use AJAX
                var form = document.createElement("form");
                form.setAttribute("method", 'post');
                //form.setAttribute("action", '/FacebookLogin.ashx');
                form.setAttribute("action", '/Home/FacebookLogin');

                var field = document.createElement("input");
                field.setAttribute("type", "hidden");
                field.setAttribute("name", 'accessToken');
                field.setAttribute("value", accessToken);
                form.appendChild(field);

                document.body.appendChild(form);
                form.submit();

            } else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook, 
                // but has not authenticated your app
            } else {
                // the user isn't logged in to Facebook.
            }
        });
    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));
</script>

<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1"></div>

关于.cshtml

@{
    ViewBag.Title = "About Us";
}

<h2>About</h2>
<p>
     @ViewBag.Message
</p>

你能告诉我如何解决这个问题,以便显示一个 FB 登录按钮,当点击它时,它会要求用户进行 FB 身份验证,将它们发回,然后我的应用程序将它们识别为登录用户?

4

1 回答 1

3

至于登录按钮,如果您在访问您的应用程序之前登录到 Facebook,您将看到面孔而不是登录按钮,恢复登录按钮的唯一方法是访问 facebook.com 并注销或可能使用 C# SDK 进行 facebook 注销。根据您的要求,这可能是也可能不是您想要的。如果这是您真正想要的,SDK 文档中有一些关于重新身份验证的内容。

我已通过删除 submit() 并用 ajax 帖子替换它来调整您的应用程序,FacebookLogin 操作已更改,并且我在 About 操作上添加了一些错误处理。您的原始应用程序可以运行,但如果您登录 Facebook,它将自动重定向到 About。

更新添加了一个不使用 Javascript 的登录链接,插入 appid 和 appsecret 并相应地调整端口号。这是从这里找到的服务器端登录示例改编而来的,它比这段代码漂亮得多:)

注意在服务器端流中传递的状态值应该是你应该在 ConnectResponse() 方法中验证的唯一值,即在 FacebookLoginNoJs 中生成一个值并确保它在 ConnectResponse 中相同以防止跨站点请求伪造

家庭控制器.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;

namespace FacebookTest.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Please log in first";

            if (Session["AccessToken"] != null)
            {
                var accessToken = Session["AccessToken"].ToString();
                var client = new FacebookClient(accessToken);

                try
                {
                    dynamic result = client.Get("me", new { fields = "name,id" });
                    string name = result.name;
                    string id = result.id;

                    ViewBag.Message = "Hello id: " + id + " aka " + name;
                }
                catch (FacebookOAuthException x)
                {

                }
            }

            return View();
        }

        public void FacebookLogin(string uid, string accessToken)
        {
            var context = this.HttpContext;
            context.Session["AccessToken"] = accessToken;
        }

        public ActionResult FacebookLoginNoJs()
        {
            return Redirect("https://www.facebook.com/dialog/oauth?client_id=MY-APPID-REMOVED&redirect_uri=http://localhost:45400/Home/ConnectResponse&state=secret");
        }

        public ActionResult ConnectResponse(string state, string code, string error, string error_reason, string error_description, string access_token, string expires)
        {
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    var client = new FacebookClient();
                    dynamic result = client.Post("oauth/access_token",
                                              new
                                              {
                                                  client_id = "MY-APPID-REMOVED",
                                                  client_secret = "MY-APP-SECRET-REMOVED",
                                                  redirect_uri = "http://localhost:45400/Home/ConnectResponse",
                                                  code = code
                                              });

                    Session["AccessToken"] = result.access_token;

                    if (result.ContainsKey("expires"))
                        Session["ExpiresIn"] = DateTime.Now.AddSeconds(result.expires);

                }
                catch
                {
                    // handle errors
                }
            }
            else
            {
               // Declined, check error
            }

            return RedirectToAction("Index");
        }

    }
}

索引.cshtml

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            //appId: 'YOUR_APP_ID', // App ID
            appId: 'MY-APPID-REMOVED', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        // Additional initialization code here
        FB.Event.subscribe('auth.authResponseChange', function (response) {
            if (response.status === 'connected') {

                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;

                var url = '/Home/FacebookLogin';
                $.post(url, { uid: uid, accessToken: accessToken }, function (data) {
                });

            } else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook, 
                // but has not authenticated your app
            } else {
                // the user isn't logged in to Facebook.
            }
        });
    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));
</script>

<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1"></div>

@Html.ActionLink("The NoJs Login", "FacebookLoginNoJs", "Home")

关于.cshtml

@{
    ViewBag.Title = "About Us";
}

<h2>About</h2>
<p>
        @ViewBag.Message
</p>
于 2012-07-15T21:58:05.203 回答