65.9K
CodeProject 正在变化。 阅读更多。
Home

集成了 Facebook OAuth API 的简单 .NET MVC 3 Web 应用程序

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.58/5 (17投票s)

2011年6月5日

CPOL

1分钟阅读

viewsIcon

109871

downloadIcon

4

将 Facebook OAuth API 集成到 ASP.NET MVC 3 网站中。

引言

在创建 .NET MVC 应用程序之前,我们必须在 Facebook 开发站点上注册将用于该网站的域名:http://developers.facebook.com/setup/。 成功注册后,我们将获得 Facebook APIKey 和 Facebook Secret。

现在让我们在 VS 中创建一个简单的 ASP.NET MVC 应用程序

net_mvc_facebook_oauth/1_1.png

我将在此示例中使用 Facebook API 按钮向用户显示另一种登录选项。 让我们以这种方式更改 _LogOnPartial.cshtml 文件

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    <fb:login-button perms="email,user_checkins" onlogin="afterFacebookConnect();" 
       autologoutlink="false" ></fb:login-button>
    <div id="fb-root" style="display:inline; margin-left:20px;"></div>
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
<script language="javascript" type="text/javascript">
    window.fbAsyncInit = function () {
        FB.init({ appId: ' -- YOUR REAL APPLICATION ID SHOUD BE HERE --', 
                  status: true, cookie: false, xfbml: true });
    };
    function afterFacebookConnect() {
        FB.getLoginStatus(function (response) {
            if (response.session) {
                window.location = "../Account/FacebookLogin?token=" + 
                       response.session.access_token;
            } else {
                // user clicked Cancel
            }
        });
    };
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//#/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });
</script>

已向控件添加以下元素

  • Facebook 登录按钮 (fb:login-button)。
  • 将包含所有 Facebook 脚本的容器 (div id="fb-root")。
  • FB 初始化脚本 (FB.fbAsyncInit)。 您**必须**将示例 appId 值替换为在 Facebook 开发站点上注册应用程序时收到的真实值。
  • afterFacebookConnect - 在用户关闭 Facebook 登录对话框窗口(成功或失败登录后)将调用的脚本。
  • 用于加载 Facebook JavaScript 库的脚本 (e.src = document.location.protocol + '//#/en_US/all.js';)。

成功登录后,我们将获得 access_token 值,现在我们可以加载详细的用户信息,存储这些信息(如果需要),并验证用户。 为此,我们将用户重定向到 Account.FacebookLogin 操作,并将 access_token 值作为参数传递给此操作。 因此,在此阶段,我们将实现“FacebookLogin”操作。 创建的操作如下所示

using System.Web.Mvc;
using System.Web.Security;
using MVCOAuth.Models;
using System.Net;
using Newtonsoft.Json.Linq;
using System;

namespace MVCOAuth.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));
            // Json.Net is really helpful if you have to deal
            // with Json from .Net http://json.codeplex.com/
            JObject jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            //     http://developers.facebook.com/docs/reference/api/user/
            string username = jsonUserInfo.Value<string>("username");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            string facebook_userID = jsonUserInfo.Value<string>("id");

            // store user's information here...
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("Index", "Home");
        }

就这样! 我们已在 MVC 站点上集成了替代 Facebook 身份验证。 登录前

net_mvc_facebook_oauth/R_1.png

成功进行 Facebook 身份验证后

net_mvc_facebook_oauth/R_2.png

希望这对某人有所帮助! 

© . All rights reserved.